How to print this box in MatLab?

1 次查看(过去 30 天)
Juan Zegarra
Juan Zegarra 2019-5-6
编辑: Adam Danz 2019-5-14
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')
Screen Shot 2019-05-06 at 8.27.00 AM.png
  1 个评论
dpb
dpb 2019-5-6
HINT: your only newline print statement is at the complete end of all code...

请先登录,再进行评论。

回答(1 个)

Adam Danz
Adam Danz 2019-5-6
编辑:Adam Danz 2019-5-14
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'

类别

Help CenterFile Exchange 中查找有关 Programming 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by