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

5 vues (au cours des 30 derniers jours)
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.

Réponse acceptée

James Tursa
James Tursa le 13 Oct 2017
Modifié(e) : James Tursa le 13 Oct 2017
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 commentaires
James Tursa
James Tursa le 13 Oct 2017
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.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by