How to print this box in MatLab?

3 ビュー (過去 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 Center および File ExchangeProgramming についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by