필터 지우기
필터 지우기

Is it available to change the end of a loop for inside it?

조회 수: 15 (최근 30일)
AMINE EL MOUATAMID
AMINE EL MOUATAMID 2019년 4월 30일
답변: NALLARASU KRISH 2023년 5월 30일
ssss.PNG
ssssss.PNG
the size of my variable out changes inside the loop for so that's why I recalculate it inside it but the loop variable i stops in the first size of the variable even sizeOut changes.
can't the endval of the loop change ? or it can't ?
  댓글 수: 4
Adam Danz
Adam Danz 2019년 4월 30일
The break would be conditional upon the size of sizeOut. In other words,
if sizeOut(1,1) == something
break
end
AMINE EL MOUATAMID
AMINE EL MOUATAMID 2019년 4월 30일
I understand but sizeOut(1,1) maybe stay in the first value and maybe changes so I can't test it with something to break the loop.
otherways the while loop is better

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

채택된 답변

Adam Danz
Adam Danz 2019년 4월 30일
편집: Adam Danz 2019년 4월 30일
You want to use a while loop for this purpose.
It might look something like this (tough to tell without seeing more of your code)
c = 2; %counter
while c <= sizeOut(1,1)
% Do something
c = c+1;
end
Another good suggestion by Stephen Cobeldick is to add a conditional break to the for-loop that exits the loop when the sizeOut variable reaches a certain size.
  댓글 수: 3
Adam Danz
Adam Danz 2019년 4월 30일
편집: Adam Danz 2019년 4월 30일
A for-loop is designed to be executed a fixed number of times and once you enter the loop you cannot change the number of expected iterations. The only options are to conditionally break to leave the loop early or to continue to skip an iteration.
A while loop, on the other hand, is designed to continually iterate until a condition is met (break and continue are also options).
AMINE EL MOUATAMID
AMINE EL MOUATAMID 2019년 4월 30일
thank you this is really helpfull

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

추가 답변 (1개)

NALLARASU KRISH
NALLARASU KRISH 2023년 5월 30일
In MATLAB, end condition of a for loop cannot be updated or changed within the for loop. Once it is set during the start of the loop, it is set until it is met.
a = 1;
b = 6;
for c = a+1 : b
c
b
fprintf('here\n');
b = b-1;
end
After seeing the above code, one might think that "here" is printed only three times. But MAT thinks otherwise.
c =
2
b =
6
here
c =
3
b =
5
here
c =
4
b =
4
here
c =
5
b =
3
here
c =
6
b =
2
here

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by