Is it possible to make a variable in the control statement of a loop change with different iterations of the loop?
1 次查看(过去 30 天)
显示 更早的评论
I´m hoping this question makes sense. Here is some loop I wrote:
(for n is an odd integer bigger than 3, and at the beginning of the loop x=1, zz=0, N=[] and X=[1:n^2])
for ii=(n-x+1)^2:-(n-x):10
zz=zz+1;
N(zz)=X(ii);
if ii==((n-x-1)^2)
x=x+2;
end
end
I was hoping that as x changes (everytime ii becomes equal to the square of a new odd integer), the interval "-(n-x)" in the control statement of the for loop would also change, and the interval would become smaller (by two). But apparently it doesn´t work that way, and the interval always stays the same as it was when I launched the loop (so for example if n=7 the interval is always 6 no matter what x equals at that point). Is there any way to make that change or to go around this problem? I´m thinking maybe I tried to be a little too fancy for my coding skills here :p
Thanks in advance!
edit : Sorry it was actually really easy I made it into a while loop and added the increment in the body of the loop, I can´t delete the question for some reason!
0 个评论
采纳的回答
Image Analyst
2017-12-7
No, the indexes are determined when the loop starts. Even if you do change 1, n, or x inside the loop, they'll take on their new value inside the loop but once they hit the end statement, the next iteration will begin with the value the index would have had as if you didn't change the values. So for example, if ii = 1, and then inside the loop you change ii to 14 it will remain 14 only within that iteration, and when the next iteration starts, ii will be 2, NOT 15. And if you change n or x, then they will have that value only within that iteration and will not cause ii to change even withing that same iteration, nor cause ii to change on the next iteration.
2 个评论
Image Analyst
2017-12-7
Yes, if you really want to do that you can convert it into a while loop. Nonetheless, I think the for loop index information I gave above might be educational for some people.
更多回答(0 个)
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!