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

2 views (last 30 days)
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.

Accepted Answer

Guillaume
Guillaume on 21 Oct 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]) = []

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!