How to print this box in MatLab?
3 views (last 30 days)
Show older comments
Hello can you please help me with the code for this box of Os' and Xs'? So far I've done this but I only print one line.
n=input('Enter length')
for i= 1:n
for j=1:n
if i==1||i==n
fprintf('x')
elseif 1==2 | 1==n-1
if j==1 |j==n
fprintf('x')
else
fprintf('o')
end
end
if(i==3)| (i==(n-2))
if j==2 |j==n-1
fprintf('o')
else
fprintf('x')
end
if i==1 | j==3 | j==n-2 | j==n
fprintf('x')
elseif j==2 | j==n-1
fprintf('o')
end
end
end
end
fprintf('\n')
1 Comment
Answers (1)
Adam Danz
on 6 May 2019
Edited: Adam Danz
on 14 May 2019
As dpb mentioned, you need to indicate when to move to the next line (which is only done at the very end of your code).
Here's an alternative I put together just for fun.
n = 10;
m = nan(n,n);
% loop through each of the 3 outer layers
for i = 1:3
m(i:n-i+1,i) = i; %left edge
m(i,i:n-i+1) = i; %top
m(end-i+1,i:n-i+1) = i; %bottom
m(i:n-i+1,end-i+1) = i; %right
end
% odd numbers become "x"s, even numbers become "o's and NaNs become empties
mcell = cell(size(m));
mcell(mod(m,2)==1) = {'x'};
mcell(mod(m,2)==0) = {'o'};
mcell(isnan(m)) = {' '};
% Print to command window as nxn char array
reshape(char(mcell),n,n)
Result:
ans =
10×10 char array
'xxxxxxxxxx'
'xoooooooox'
'xoxxxxxxox'
'xox xox'
'xox xox'
'xox xox'
'xox xox'
'xoxxxxxxox'
'xoooooooox'
'xxxxxxxxxx'
0 Comments
See Also
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!