How to print this box in MatLab?

2 visualizzazioni (ultimi 30 giorni)
Juan Zegarra
Juan Zegarra il 6 Mag 2019
Modificato: Adam Danz il 14 Mag 2019
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 Commento
dpb
dpb il 6 Mag 2019
HINT: your only newline print statement is at the complete end of all code...

Accedi per commentare.

Risposte (1)

Adam Danz
Adam Danz il 6 Mag 2019
Modificato: Adam Danz il 14 Mag 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'

Categorie

Scopri di più su Programming in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by