Find at least 5 consecutive values above a certain threshold in a vector with the certain gap?

7 views (last 30 days)
Hi All,
I have a 3D matrix (longitude x latitude x time). I want to find the consecutive values above a certain threshold with two conditions.
first : have to 5 coonsecutive above threshold
second: neglecting the gap with the maximum =2.
For example:
A>B
A= 5 6 7 8 9 4 5 6 3 4 5 4 6 9 3 4 4 6
B= 4 4 6 7 8 3 6 4 2 3 4 7 7 8 2 3 3 4
I want the result to be :
A= 5 6 7 8 9 4 5 6 3 4 5 ( neglecting 1 gap in the 6th number which A<B. because the maximum gap is 2, so the 6th number is included in group).
The rest numbers are not included in the group because they are only 4 consecutive value after two gaps.
I have this code (thanks to Akira Agata:
% Sample data (3:lat, 3:lon, 50:days)
rng('default'); % for reproducability
a = rand(3,3,50);
b = rand(3,3,50)*0.4;
% Extract values which satisfies a > b for more than 5 consecutive days
idx = a > b;
[latGrid, lonGrid] = meshgrid(1:3,1:3);
tResult = table(latGrid(:),lonGrid(:),'VariableNames',{'lat','lon'});
tResult.extData = cell(height(tResult),1);
for kk1 = 1:height(tResult)
% break down into 1-D problem and apply the original answer
lat = tResult.lat(kk1);
lon = tResult.lon(kk1);
idx0 = bwareafilt(squeeze(idx(lat,lon,:)),[5,Inf]);
a0 = squeeze(a(lat,lon,:));
label = bwlabel(idx0);
N = cell(max(label),1);
for kk2 = 1:max(label)
N{kk2} = a0(label == kk2);
end
tResult.extData{kk1} = N;
end
However, this code does not include the second condition (neglecting gap with the maximum 2).
So, how do I put the second condition?
Thank you very much
Your help is greatly appreciated.
  5 Comments
Ahmad Bayhaqi
Ahmad Bayhaqi on 6 Jun 2021
Thank you before,
Yes, the example that I gave is 1D matrix. That just shows my logical thinking. I tried to implement it into the 3D matrix with the attached script.
However, the script only covers the first condition. I do not know how to put my second condition into the script.
I revised my example in @darova's comment.
MANON QUIPOURT
MANON QUIPOURT on 14 Jul 2022
Did you manage to resolve your code ? Cause I have the same problem, and I don't know how to deal with the 2-days gap.
Thank you

Sign in to comment.

Answers (1)

daniel mitchell
daniel mitchell on 14 Jul 2022
Edited: daniel mitchell on 14 Jul 2022
There are nicer ways to implement but this way, it is very easy to adjust to multidimensional
a = [5 6 7 8 9 2 5 6 3 4 5 8 6 7 3 4 4 6];
b = [4 4 6 7 8 3 6 4 2 3 4 7 7 8 2 3 3 4];
temp = double(a>b);
temp = imfilter(temp,[0 0 0 0 1 1 1 1 1]);
temp = temp >= 5;
temp = double(imfilter(temp,[1 1 1 1 1 0 0 0 0]));
tempGap = imfilter(temp,[1 0 0 0 1]);
tempGap = (tempGap == 2);
r = (logical(temp) | tempGap);
a(r)
ans = 1×12
5 6 7 8 9 2 5 6 3 4 5 8

Categories

Find more on Resizing and Reshaping 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!