I have written an algorithm that finds the local maxima and minima in a signal.
[id_max, id_min] = find_max_min(signal);
I would like now to check: if the alterantion of maxima and minima is respected
i.e. id_max(1)<id_min(1)<id_max(2)<id_min(2)<...
we could start with a minimum..this is not known
Suppose that:
id_max = [1 3 5 7 10 14 20];
id_min = [2 4 6 8 16 19];
I would like to have 2 vectors missing_max
missing_min
indicating the location of the missing maxima and minima.
A missing maximum (minimum) occours when between two consecutive minima (maxima) in id_min (id_max)
there is not a maximum (minimum).
In this example a maximum is missing in the 7th position of id_max because in id_min there are two consecutive values (16 19) without a maximum between.
Then we have
missing_max = [7]
missing_min = [5]
since
id_max = [1 3 5 7 10 14 X 20];
id_min = [2 4 6 8 X 16 19];
(with X I marked the missing values)
If the alternation is correct the vectors should be empty. Can you suggest an efficient way to do that without for loops?
Thanks in advance
Here's a script that you can adapt to a function if you want:Caveats on IDs:
id_min
andid_max
are rows (even if empty);Later edit:
New version of the code, based on new explanations about the definition:
However, the code contains a subtle bug. The bug will be removed by either the person that asked the question, or by me after he/she improves the question in such a way that is really clear what's asked for. :-)Due the fact that we have 2 virtual extremums (one max and one min, at ID = −∞) is possible that the first missing extremum will be marked twice: once at −∞ and once at the first element of the ID list.unique()
will take care of that (though is too much of a function call to check if the first 2 elements of an array have the same value)