Find a rising and decreasing trend on the MATLAB curve

a=[2 3 6 7 2 1 0.01 6 8 10 12 15 18 9 6 5 4 2]. 

Here is an array in which I need to extract the exact values ​​where the up and down trend begins.

the output for array a will be [2(first element) 2 6 9]

 a=[2 3 6 7 2 1 0.01 6 8 10 12 15 18 9 6 5 4 2]. ^ ^ ^ ^ | | | | 

Please help me get the result in MATLAB for any such type of array.

+4
source share
2 answers

This is a great place to use the diff function.

Your first step will be this: B = [0 diff(a)]

The reason for adding 0 is to keep the matrix of equal length due to how the diff function works. It will start with the first element in the matrix, and then report the difference between this and the next element. There is no leading element before the first, so it just truncates the matrix with one element. We add zero because there are no changes, since this is the initial element.

If you look at the results in B , it’s now completely obvious where the inflection points are (where you go from positive to negative).

To do this programmatically, there are a number of things you can do. I usually use a little multiplication and the find .

Result = find(B(1:end-1).*B(2:end)<0)

This will return the index where you are at the top of the inflection. In this case, it will be:

 ans = 4 7 13 
+1
source

You just need to find where the difference sign between consecutive numbers changes. With some common sense and diff , sign, and find functions, you get this solution:

 a = [2 3 6 7 2 1 0.01 6 8 10 12 15 18 9 6 5 4 2]; sda = sign(diff(a)); idx = [1 find(sda(1:end-1)~=sda(2:end))+2 ]; result = a(idx); 

EDIT:

The sign function puts things up when there are two consecutive numbers that are the same, because sign(0) = 0 , which is falsely identified as a trend change. You will have to filter them out. You can do this by first removing successive duplicates from the source data. Since you only need the values ​​at which the trend begins, and not the position at which it begins, this is easiest:

 a(diff(a)==0) = []; 
+5
source

All Articles