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!

采纳的回答

Image Analyst
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 个评论
Florent Dueme
Florent Dueme 2017-12-7
Thanks a lot for the answer!
I found a way to go around the problem it´s actually not difficult at all once I accepted that I couldn´t change the control statement!
Image Analyst
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 个)

类别

Help CenterFile Exchange 中查找有关 循环及条件语句 的更多信息

Community Treasure Hunt

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

Start Hunting!