Delete elements from a vector that are less or equal than the elements immediately before them
3 次查看(过去 30 天)
显示 更早的评论
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.
0 个评论
采纳的回答
Guillaume
2015-10-21
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]) = []
更多回答(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!