'How do I start counting when below a threshold and stop counting above the same threshold in a timeseries? [closed]

I modeled wind speed data for a whole year and now I want to count the amount of consecutive hours that the wind is below a certain threshold. I have to find out the maximum consecutive hours of wind below that threshold. Therefore it should start counting when it hits the threshold and stop counting when the value gets above the threshold again. This will happen multiple times during the year so, like I mentioned, I looking for the max consecutive hours

Windspeed_hourly_mean = xlsread('Windspeed_hourly.xlsx','D3:D8762');
WHM=Windspeed_hourly_mean;
threshold = 3;

    isBelow = (WHM < threshold); % gives us a vector of logical values
    isBelow = [false, isBelow, false]; % make sure the vector starts and ends with false
    transitions = diff(isBelow); % gives 1 where false->true and -1 where true->false 
    starts = find(transitions==1); % indexes of where each period starts
    ends = find(transitions==-1); % indexes of where each period ends
    durations = ends - starts;
    max(durations) % largest duration


Solution 1:[1]

If you have a 1 x n vector of hourly wind speed values windSpeed and your threshold is threshold then:

isBelow = (windSpeed < threshold); % gives us a vector of logical values
isBelow = [false, isBelow, false]; % make sure the vector starts and ends with false
transitions = diff(isBelow); % gives 1 where false->true and -1 where true->false 
starts = find(transitions==1); % indexes of where each period starts
ends = find(transitions==-1); % indexes of where each period ends
durations = ends - starts;
max(durations) % largest duration

Adding false to the start and end of the isBelow vector is needed so that there is a start before every end, and so that the ends vector is the same length as the starts vector.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 nekomatic