Getting values from a for loop when specific condition met
13 次查看(过去 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!