Getting values from a for loop when specific condition met
조회 수: 8 (최근 30일)
이전 댓글 표시
I am doing a loop, and want the iteration stops when condition of x = 5 however, the code terminates before x=5 ?
So any help please
clear all;
clc;
x=[1 2 3 4 5 6 7 8 9 10];
for n=1:10
if x(n)>= 5;
break
end
disp('how many iteration done now');
final(n,:)=x(n)
z(n,:)=x(n)+2
end
댓글 수: 1
Rik
2019년 8월 25일
It doesn't calcluate anything for n=5, because you tell Matlab to stop before that. What is your question?
채택된 답변
dpb
2019년 8월 25일
break is like drawing the "Go To Jail" card in Monopoly--you "go directly to jail, do not pass GO, do not collect $200". Here when you get to the conditional and it is satisfied, then the code immediately goes to the next line of code after the terminating end of the for loop and so the other code isn't executed that last iteration--the loop did do five iterations here because it took until then for x(n) to be >=5; just that you didn't do anything at all in the loop other than the test.
Perhaps your expectations could be met simply by reordering:
...
for n=1:10
disp('how many iteration done now');
final(n,:)=x(n)
z(n,:)=x(n)+2
if x(n)>= 5, break, end
end
...
Then again, that assumes that what happens now is what you want to happen for the loop for all iterations that it does do...
댓글 수: 6
dpb
2019년 8월 26일
편집: dpb
2019년 8월 26일
"Optional" in that it is an optional input to find(), not that it is optional to use it in this case to find the first location in x that satisfies the condition which is what your break logic is doing.
I added 2 because that's what your code does... :)
It produced identically the same results as your code here...
>> x=1:10;
>> for n=1:10
disp('how many iteration done now');
final(n,:)=x(n);
z(n,:)=x(n)+2;
if x(n)>= 5, break, end
end
how many iteration done now
how many iteration done now
how many iteration done now
how many iteration done now
how many iteration done now
>> [final z(:,5)]
ans =
1 3
2 4
3 5
4 6
5 7
>>
Your code above w/o the intermediate results while mine produced:
>> final=find(x>=5,1);
>> z=x(1:final)+2;
>> final
final =
5
>> z.'
ans =
3
4
5
6
7
>>
with the assumption as before that there really wasn't any need for final to be an array and the desired result was that for z when the condition is met.
Now, if that isn't the result wanted, then the actual problem definition needs clarification. So, if the problem is really the statement "I meant, I need from x array all the numbers that met the conditions written." then that's just
z=x(x>=5);
using logical addressing/indexing, one of the most powerful of Matlab features. That isn't what your code actually does, but maybe that was the real question underneath the one you asked.
추가 답변 (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!