Access to for loop index

79 views (last 30 days)
Steven
Steven on 6 May 2011
I have a for loop in which I loop over a sequence of numbers, like this:
for i = [start:step:end]
%do stuff
end
In the body, it would be useful if I could access the "real" index of the loop. Put another way, I want to access the number of times the loop has been run through. For example, if start = 2, step = 3, and end = 17, then when the index i is at 5, the "real" index is 2. On the next loop, when i goes up to 8, the "real" index goes up to 3, and so on. I could generate a vector and then just loop through it, but that would require a lot of extra space, and would obscure the code. I could also make my own special variable and just increment it every time through, but if there already is such a variable somewhere, I'd like to just access it rather than make more variables. Also, If I wanted to have nested loops, how would I look at the "real" index of the outer loop while in the body of the inner? Is that even possible?

Answers (2)

Teja Muppirala
Teja Muppirala on 6 May 2011
There is no special variable. You have to do it yourself:
i_list = [start:step:end]
for n = 1:numel(i)
i = i_list(n);
%do stuff
end
For nested loops it's similar. You have to keep track of things yourself. For example:
real_outer = 0;
for m = 2:3:18
real_inner = 0;
real_outer = real_outer + 1;
for n = 5:5:50
real_inner = real_inner + 1;
%Do stuff
end
end

Walter Roberson
Walter Roberson on 6 May 2011
If you are working with integers, or with steps that are a power of 2 (e.g., 1/2, 1/64), then
index = 1 + (i - start)/step
Be warned that if you are attempting to use a step of (say) 0.01 then this calculation might not give you the correct answer.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Tags

Products

Community Treasure Hunt

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

Start Hunting!