Maryam
Maryam

Reputation: 35

How to 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 is always ascending until the invalid value (here for ex. 55), I need to find the indices of this element and remove all elements after that. my desired vectror is [20 30 40 50 60] any suggestion?

Upvotes: 3

Views: 85

Answers (1)

m.s.
m.s.

Reputation: 16334

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 search the first index of those differences that is less than zero and remove this and all succeeding elements.

>>> 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

Upvotes: 8

Related Questions