How could i shorten my for loop code?
5 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
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 Commenti
Risposta accettata
José-Luis
il 27 Set 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 Commenti
José-Luis
il 27 Set 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.
Più risposte (0)
Vedere anche
Categorie
Scopri di più su Matrix Indexing 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!