Performing operation with loop index inside for-loop doesn't work as expected

5 ビュー (過去 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.

採用された回答

James Tursa
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
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.
Taniel Goetcherian
Taniel Goetcherian 2017 年 10 月 13 日
Good to know, thanks!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by