How do I find all sequences of at least 3 in which values are increasing or decreasing?

13 views (last 30 days)
I have a two-vector array in which I need to find all sequences of at least three where both vectors simultaneously increase or decrease. I will want to know the index, length, and change over each sequence.
There must be an eloquent way to do this!
Much appreciated! -D.

Answers (2)

Oleg Komarov
Oleg Komarov on 3 Aug 2012
These functions will get you started:
  • diff() the two vectors
  • Use sign() to retain only info about increase, decrease (or use logical indexing).
  • Then you can use my submission findseq() to find sequences of increases and decreases.

Image Analyst
Image Analyst on 3 Aug 2012
Edited: Image Analyst on 4 Aug 2012
It's pretty easy if you have the Image Processing Toolbox. Just use diff() on the two vectors. Threshold and AND the two results to find where BOTH are increasing or decreasing. Then pass that into bwareaopen() to throw out sequences of less than the length you specify. Then use regionprops() to measure what's left. You can get indexes, lengths, and values all in one call. You can pass the values into max() and min() to get the range. It's only a few lines, something like
clc;
clearvars;
workspace;
% Define sample vectors.
v1 = [1 1 1 2 3 4 1 1 1 1 3 4 5 6 7 8 1 1 1 1 1 2]
deltav1 = diff(v1)
v2 = [1 1 2 3 4 5 2 2 3 4 5 1 3 4 7 8 9 0 0 0 1 2]
deltav2 = diff(v2)
% Find out where each has increasing runs.
increasingv1 = [0 deltav1>0]
increasingv2 = [0 deltav2>0]
% Find out where BOTH have increasing runs at the same time.
bothIncreasing = increasingv1 & increasingv2
% Get rid of any stretches that are 2 or fewer.
% Keep only stretches that are 3 or longer.
longStretches = bwareaopen(bothIncreasing, 3)
% Now measure the length (area) of those stretches.
measurements = regionprops(longStretches, 'Area', 'PixelIdxList'); % Get lengths, indexes, values, etc.
% Get all the lengths into one array, if needed.
allLengths = [measurements.Area]
% Determine how many regions there were.
numberOfRegions = length(measurements)
% Now print out the elements for those regions
% in both the original vectors.
for r = 1 : numberOfRegions
fprintf('\nNow, for region %d:\n', r);
thisRegionsElements = measurements(r).PixelIdxList
v1Elements = v1(thisRegionsElements)
v2Elements = v2(thisRegionsElements)
end

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!