0

I have a row matrix as follows

a=[1 2 3];

The for loop has been implemented as follows

 for i=1:a(1,1:size(a,2))
    disp(i);
    disp("Hello");
end

Based on the values of the row matrix Hello has to be printed 6 times(i.e 1+2+3) but it gets printed only once. How can I iterate along the row matrix and get Hello printed 6 times?

Kushan Peiris
  • 167
  • 3
  • 15

1 Answers1

4
a=[1 2 3];
for ii=1:sum(a)
    disp("Hello")
end 

1:a(1,1:size(a,2)) == 1:a(1,[1 2 3]) == 1:a(1,1) == 1:1 == 1 actually creates an array containing the number 1 (more specific: a(1), as 1:[1 2 3] will evaluate to 1:1, discarding all elements further on in the vector). Given the number 6 you mention I take it you want the sum of all elements in a which is given by sum.

Final word of caution: please refrain from using i and j as variable names, as they also denote the imaginary unit.


Reading your comment you probably need a nested loop, as the entries of a might not be monotonically increasing:

k = 1; % counter to show which iteration you're in
for ii = 1:numel(a) % for all elements of a do
    for jj = 1:a(ii) % do the following a(ii) times
        disp('Iteration %d', k)
        disp('Hello')
        k = k+1; % increase iteration count
    end
end

Note that both methods fail (obviously) when a does not contain strictly non-negative integer values.

Adriaan
  • 17,741
  • 7
  • 42
  • 75
  • not the sum I want to iterate it once, then twice and then thrice since I may need to implement such for loops in future. so how can I iterate in that manner? – Kushan Peiris Mar 29 '18 at 13:04
  • Iterate once, then twice, then three times means you want to iterate on `sum(a)`. I don't see what the problem is in that case? – Adriaan Mar 29 '18 at 13:05
  • @KushanPeiris I think I solved your problem, see the edit, but this smells of an [XY problem](https://meta.stackexchange.com/q/66377/325771) so I think you're better of asking a new question with the actual code instead of an oversimplified example, so we can take a look whether the approach you're currently using is a good one (I suspect not, as this is a very contrived usage of loops). – Adriaan Mar 29 '18 at 13:37