Access to for loop index

79 visualizaciones (últimos 30 días)
Steven
Steven el 6 de Mayo de 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?

Respuestas (2)

Teja Muppirala
Teja Muppirala el 6 de Mayo de 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 el 6 de Mayo de 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.

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Etiquetas

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by