How could i shorten my for loop code?

5 visualizzazioni (ultimi 30 giorni)
Dan Po
Dan Po il 27 Set 2016
Commentato: Dan Po il 29 Set 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!

Risposta accettata

José-Luis
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
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.
Dan Po
Dan Po il 29 Set 2016
What i meant is is there a way to consolidate these two for loops (the starred lines)?
for i= 1:ceil(row/2);
* for j=1:row-i %used to print spaces on one line
* fprintf(' ')
* end
* for k=1:2*i-1 %used to print stars on same line
* fprintf('*')
* end
fprintf('\n')
end
I dont think there is. My for loop does what your repmat does. So far i could reduce my code by using your style of index increment then decrement as so:
before: for i= 1:ceil(row/2);
and: for j=ceil(row/2)-1:-1:1
-------------------------
after: for i= [1:(row+1)/2,(row-1)/2:-1:1]
This reduction leads to my code being 2 lines longer than your code. You win this time... Lol.
Also, it seems like your code could be reduced to a super short:
numRows = 3 % input('enter something');
matSpaceStar=[[1:2:numRows,numRows-2:-2:1];[numRows-[1:2:numRows,numRows-2:-2:1]]/2];
for ii = matSpaceStar
fprintf([repmat(' ',1,ii(2)),repmat('*',1,ii(1)),'\n']);
end
Earlier, were you hinting that there is a shorter way to make the shape than using a for loop?
If you could spare more time, could you tell me?
I thought about it, but have run out of time and need to get back to homework. This problem is pretty fun.
Thank you for your help!

Accedi per commentare.

Più risposte (0)

Community Treasure Hunt

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

Start Hunting!

Translated by