is it allowed to update the cycle variable?

답변 (1개)

Walter Roberson
Walter Roberson 2015년 10월 17일

1 개 추천

You can change the index variable within a "for" loop, and the change in value will last to the end of the iteration. As soon as the next iteration starts the new value assigned will ignore any change you made. For example,
for K = 1 : 5
disp(K); %first time through would be 1, second time through would be 2
K = K * 10; %allowed
disp(K); %first time through would be 10, second time through would be 20
end
Notice that the second time through the loop the change of K from 1 to 10 in the first iteration has no effect on what happens for the second iteration.

댓글 수: 4

per isakson
per isakson 2015년 10월 17일
Yes, but ...
Walter Roberson
Walter Roberson 2015년 10월 17일
The question was "is it allowed" and the answer is "Yes". And now I have clarified the effect it has.
per isakson
per isakson 2015년 10월 18일
편집: per isakson 2015년 10월 18일
Yes, your answer is correct. I don't question that.
However, the documentation says: "Avoid assigning a value to the index variable within the loop statements." And I cannot think of a good reason to do it.
Walter Roberson
Walter Roberson 2015년 10월 18일
I cannot think of a good reason to do it either.

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터File Exchange에서 Matrix Indexing에 대해 자세히 알아보기

질문:

2015년 10월 17일

댓글:

2015년 10월 18일

Community Treasure Hunt

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

Start Hunting!

Translated by