Hadiza Hamza
Hadiza Hamza

Reputation: 37

matlab for loop to iterate for every 10 steps

I am trying to iterate every 10 steps in a code using for loop. the code is written below;

for i=10:10:30 
 for j=20:10:40
   k=i+j
 end
end

So, the first iteration will be 10:20, then 20:30 and finally 30:40.But I keep getting errors in my code when i use that.However, if I just typed in 10:20 or 20:30,it works okay.

Upvotes: 0

Views: 211

Answers (1)

Suever
Suever

Reputation: 65430

Having a nested for loop like you have written is not going to yield the results you expect because of the ordering of the loops. If we look at the value of i and j at the time of assignment of k, we'll see the following values.

i   j
10  20
10  30
10  40
20  20
20  30
20  40
30  20
30  30
30  40

If you want instead for k to be equal to 10:20, then 20:30 and finally 30:40, then you'll need to do something like this

starts = 10:10:30;
ends   = 20:10:40;

% Only use a single for loop
for k = 1:numel(starts)
    k = starts(k):ends(k);

    % Do stuff with this k
end

Upvotes: 1

Related Questions