# How do I start counting when below a threshold and stop counting above the same threshold in a timeseries?

5 views (last 30 days)
Hans Wagener on 25 Apr 2022
Answered: Fabio Freschi on 6 Oct 2023
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. The arrows show the possible longest periods below a threshold of 2. How can I find out which period is the longest and how long it is?

Umang Pandey on 6 Oct 2023
Hi Hans,
I understand that you want to count the number of consecutive hours based on a certain threshold.
The following MATLAB Answer where the user wants to count the number of times the signal is above certain threshold, might be of help:
Best,
Umang

Fabio Freschi on 6 Oct 2023
Below you can find a possible solution that does not require any toolbox
% signal length
N = 100;
% threshold
t = 0.5;
x = rand(N,1);
% plot
figure, hold on
plot(1:N,x,'o-');
plot([1 N],[t t])
% find values below threshold
y = x < t;
% plot
plot(find(y),x(y),'*');
% find changes in vector y
f = find(diff([0; y; 0] == 0));
% start indices of consecutive values below threshold
s = f(1:2:end);
% count the number of consecutive values below threshold
c = f(2:2:end)-s;
% report on plot
text(s,x(s),num2str(c),'FontSize',14)