How could i shorten my for loop code?
5 次查看(过去 30 天)
显示 更早的评论
I made a script to print out a diamond, but would like to make my script shorter. Only for loops are allowed. Is there a different logical way that could eliminate some for loops?
Here is the code:
row=input('enter an odd number: \n');
for i= 1:ceil(row/2);
for j=1:row-i
fprintf(' ')
end
for k=1:2*i-1
fprintf('*')
end
fprintf('\n')
end
for j=ceil(row/2)-1:-1:1
for q=1:row-j
fprintf(' ')
end
for k=2*j-1:-1:1
fprintf('*')
end
fprintf('\n')
end
%this is what it prints:
row= 9
*
***
*****
*******
*********
*******
*****
***
*
Also, the index logic could probably be simpler. Thanks!
0 个评论
采纳的回答
José-Luis
2016-9-27
numRows = 25
numStars = [1:2:numRows,numRows-2:-2:1];
numSpaces = (numRows - numStars) / 2;
If you really want a loop:
for (ii = [numStars;numSpaces])
spacePrint = repmat(' ',1,ii(2));
starPrint = repmat('*',1,ii(1));
fprintf([spacePrint,starPrint,'\n']);
end
3 个评论
José-Luis
2016-9-27
My pleasure. Seeing (and trying to understand) how other people do it is a good way to learn. I guess that's how I learned most of what I know now. It just takes time.
In don't understand what you mean by merge the two sections.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!