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?

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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?
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?
@KushanPeiris I think I solved your problem, see the edit, but this smells of an XY problem 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).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.