how to break the loop
3 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
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 Commenti
Guillaume
il 11 Gen 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.
Risposta accettata
Guillaume
il 11 Gen 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
Più risposte (0)
Vedere anche
Categorie
Scopri di più su Loops and Conditional Statements in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!