Performing operation with loop index inside for-loop doesn't work as expected
4 次查看(过去 30 天)
显示 更早的评论
Hi I'm trying to print an upside-down triangle of hash marks using a for loop. Here's what I've got so far:
n=input('How many hashtags would you like to print today? : ');
m=floor(n/2);
%{
'm' is the height (or rather 'depth') of the triangle,
currently only works correctly for odd numbers,
will figure out even numbers later
%}
hash(1:n)='#';
fprintf([hash '\n'])
for row=1:m
space(1:row)=' ';
fprintf(space)
new_hash(1:n-2*row)='#';
fprintf([new_hash '\n'])
%{
that new_hash bit is supposed to shorten the length
of hash marks on each iteration, why does this not work??
%}
end
So when I input 7, I get:
#######
#####
#####
#####
But I want to get:
#######
#####
###
#
Any help on how to fix this (or an entirely new approach, as long as it uses a for-loop) would be greatly appreciated.
0 个评论
采纳的回答
James Tursa
2017-10-13
编辑:James Tursa
2017-10-13
You don't set the trailing elements of new_hash to spaces on each iteration, or clear new_hash each iteration, so those trailing hash marks remain. What if you do this:
for row=1:m
clear new_hash
:
etc
If you are running this as a script, you will want to do this also each iteration:
clear space
Alternatively, you could set these variables directly within your loop and then not have to worry about clearing them each iteration. E.g.,
space = repmat(' ',1,row);
new_hash = repmat('#',1,n-2*row);
3 个评论
James Tursa
2017-10-13
When you use indexing on the left hand side, it is only those specific indexed elements that get changed. All of the other elements remain unchanged.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!