how to break the loop
조회 수: 5 (최근 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!