How do I find all sequences of at least 3 in which values are increasing or decreasing?
이전 댓글 표시
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.
답변 (2개)
Oleg Komarov
2012년 8월 3일
0 개 추천
Image Analyst
2012년 8월 3일
편집: Image Analyst
2012년 8월 4일
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
카테고리
도움말 센터 및 File Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!