How could i shorten my for loop code?
5 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Dan Po
am 27 Sep. 2016
Kommentiert: Dan Po
am 29 Sep. 2016
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 Kommentare
Akzeptierte Antwort
José-Luis
am 27 Sep. 2016
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 Kommentare
José-Luis
am 27 Sep. 2016
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.
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!