how to break the loop
4 次查看(过去 30 天)
显示 更早的评论
I have a matrix p;
0.1996
0.4428
0.5227
0.8407
0.8929
0.9102
0.9528
0.8986
now, i only need points until they are increasing. Once the value decreases i need to break the loop and end the process. here i have tried to use the loop,
for i=1:length(p)
if p(i,1)<p(i+1,1)
one(i,:)=p(i+1,:)
else h=p(i,:)
end
end
but it only gives the result till 0.9102. I also want to include the value 0.9528 and then break the loop.(i need to break the loop here because my matrix is nearly 100*2 and this condition might be true in the next rows). What am i doing wrong?
2 个评论
Guillaume
2018-1-11
The code you've shown is guaranteed to result in an index exceeds matrix dimension error, so it's unlikely that it only gives the result till 0.9102 since it will error before completion.
采纳的回答
Guillaume
2018-1-11
What am i doing wrong?
- Using length with a matrix ( length can be the number of rows or columns)
- Indexing past the end of the matrix. When i is the index of the last row p(i+1, 1) is not valid. This will result in and index exceeds matrix dimension error
- Growing the one array inside the loop
- Using a loop
To break out of a loop, you use break.
for i = 1:size(p, 1) %do not use length on matrices!
if somecondition
dosomething
else
break; %quit the loop
end
end
But the loop is a complete waste of time:
idxstop = find(diff(p(:, 1)) < 0, 1); %find index of first value where the difference is negative
one = p(1:idxstop, :) %and extract all rows up to that index
更多回答(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!