how to break the loop

14 Ansichten (letzte 30 Tage)
Busy Bee
Busy Bee am 11 Jan. 2018
Kommentiert: Busy Bee am 11 Jan. 2018
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 Kommentare
Guillaume
Guillaume am 11 Jan. 2018
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.
Busy Bee
Busy Bee am 11 Jan. 2018
I have 100*2 matrix. I am using the code only for the first column.

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Guillaume
Guillaume am 11 Jan. 2018
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

Weitere Antworten (0)

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by