Delete elements from a vector that are less or equal than the elements immediately before them
5 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Steve Carroll
le 21 Oct 2015
Commenté : Steve Carroll
le 21 Oct 2015
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 commentaires
Réponse acceptée
Guillaume
le 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]) = []
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!