How can I find the descending part of a vector and remove it?

I have a vector like A = [20 30 40 50 60 55 54 60 70]

. It always goes back to an invalid value (here for ex. 55

), I need to find the indices of that element and remove all elements after it. my desired vectror [20 30 40 50 60] any suggestion?

+3


source to share


1 answer


short answer:

A(find(diff(A)<0,1)+1:end) = []

      

longer answer with explanation:

diff

calculates the difference between adjacent elements:



>> diff(A)

ans =

10    10    10    10    -5    -1     6    10

      

We then look for the first index of those differences that is less than zero, and remove this and all subsequent items.

>>> idx = find(diff(A)<0,1)+1

idx =

 6

>>> A(idx:end)

ans =

55    54    60    70

>> A(idx:end) = []

A =

20    30    40    50    60

      

+8


source







All Articles