MATLAB: How to compare a group of values in a data set to each other using vectorization

vectorization

Hi!
I have two very large vectors: X and T, where one is measured power and the other one is time of each measurement. First I want to apply conditions to X, namely finding drops in power. I then want to apply constraints to these drops must be longer than t time. The time between each data point is equal.
The first part could be done like this
diff_X = diff(X);
drops_X = diff_X < x; % drops_X now contains all the drops in power
% Now I want to filter out all the drops that are shorter in duration than t, and it must be vectorized.
Thanks

Best Answer

Basically you want to find the duration of each run of power drop. As you've already established finding the power drops is a simple diff:
ispowerdrop = diff(X) < x;
which produces a logical vector. In that logical vector a sequence of [0 1] will indicate the start of a power drop, and a sequence of [1 0] will indicate the end. Other possible sequences are [0 0] (out of a power drop) or [1 1] (in a power drop). The diff of these sequences is 1, -1, 0 and 0 respectively, so finding the location of 1 and -1 in the sequence is all you need to find the start and end of the drops.
transitions = diff([false, ispowerdrop, false]); %replace , by ; if X is a column vector
startdrop = find(transitions == 1) + 1;
enddrop = find(transitions == -1);
I surrounded ispowerdrop by false to make sure you detect the start and end of power drop if they are at the beginning/end of the vector.
The duration of each power drop is then:
powerdropduration = T(enddrop) - T(startdrop);