Delete elements from a vector that are less or equal than the elements immediately before them

3 Ansichten (letzte 30 Tage)
Hello
I would like to delete all the elements in a vector that are equal or less than the elements immediately before them. If I use a "for" loop, the vector changes its size when the previous condition is met and I get an error because the last element of the vector cannot be accessed.
Example: time = [0; 1; 2; 2; 3; 4; 5; 6];
for i = 1:(length(time)-1) if time(i+1) <= time(i) time(i+1) = []; end end
Error message: "Attempted to access time(8); index out of bounds because numel(time)=7."
Many thanks in advance.

Akzeptierte Antwort

Guillaume
Guillaume am 21 Okt. 2015
The solution to your problem is to collect the indices to delete in the loop and perform the deletion all at once after the loop.
Even better, is not to use a loop at all
time = [0; 1; 2; 2; 3; 4; 5; 6];
time([false; diff(time) <= 0]) = []

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