MATLAB: How could i shorten the for loop code

simple code

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!

Best Answer

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
Related Question