필터 지우기
필터 지우기

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