Count the number of days between two conditions

1 view (last 30 days)
Eli
Eli on 11 Apr 2023
Edited: Matt J on 11 Apr 2023
Dear all,
  1. I have temperature (T) daily data in 1992. I want to count the days between T > 5 for > 5 days & T < 5 for > 5 days.
  2. I am able to determine the index when T > 5 & T < 5 but do not know how to proceed any further.
load('Test.mat');
f1 = find(T > 5);
f2 = find(T < 5);
How do I go about doing this? Thank you very much.

Answers (2)

Walter Roberson
Walter Roberson on 11 Apr 2023
There is a very useful trick to use:
mask = reshape(T,1,[]) > 5;
starts = strfind([0 mask], [0 1]);
stops = strfind([mask 0], [1 0]);
Now starts(K) and stops(K) together indicate indices of the beginning and end of runs of T > 5; you can calculate durations by looking at the difference between them.
Careful, though: If the data were [2 6 3] then mask would be [0 1 0] and starts would be 2 and stops would also be 2. The run starts at index 2 and ends at index 2, which is duration 1.
Now, you can filter those runs out to only find the ones of sufficient duration. Or you can modify the strfind() search. If you extend the [0 1] to [0 1 1 1 1 1] and [1 1 1 1 1 0] in the other one, you only match runs of at least 5. But when you do that you will find you need to adjust the indices returned by stops.
What do you want to do in the case of T being exactly 5 ? Should [7 8 5 7 9 8] qualify as a run of 6 days, or does it get disqualified because exactly 5 is not > 5 ?

Matt J
Matt J on 11 Apr 2023
Edited: Matt J on 11 Apr 2023
I want to count the days between T > 5 for > 5 days & T < 5 for > 5 days.
I hope you realize that this event occurs multiple times throughout your attached T data. Using this FEX download,
I find, in fact that it happens 9 times:
[s1,e1,r1]=groupLims( groupTrue(T>5) );
[s2,e2,r2]=groupLims( groupTrue(T<5) );
s=e1(r1>5);
e=s2(r2>5);
n=find(e>s(1),1,'first');
m=min(numel(s), numel(e)+1-n );
Start=s(1:m);
Duration=e(n:n+m-1)-Start-1;
result=table(Start,Duration)
result =
9×2 table
Start Duration
_____ ________
20 2
29 5
45 12
69 0
75 18
292 1
308 12
330 0
349 5

Categories

Find more on Characters and Strings in Help Center and File Exchange

Products


Release

R2022a

Community Treasure Hunt

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

Start Hunting!