Kushan Peiris
Kushan Peiris

Reputation: 167

Iterating over the sum of values using a loop

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?

Upvotes: 0

Views: 83

Answers (1)

Adriaan
Adriaan

Reputation: 18197

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.

Upvotes: 4

Related Questions