Access to for loop index
79 次查看(过去 30 天)
显示 更早的评论
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?
0 个评论
回答(2 个)
Teja Muppirala
2011-5-6
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
0 个评论
Walter Roberson
2011-5-6
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.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!