## Calculate number of hours below a threshold temperature

### Paul Fremeau (view profile)

on 19 Jul 2018
Latest activity Commented on by Paul Fremeau

on 20 Jul 2018

### Kelly Kearney (view profile)

I have a big timetable with temperature recorded every 10 minutes. I want to calculate the number of hours per day below a threshold temperature. Any ideas? The timetable is important because my original data is missing some timesteps, and I use retime() to fill in the blanks.
I tried using a for loop along with an if statement, but they don't seem to work with timetables.
I also tried converting the timetable back to an array, but ran into difficulties. My guess is that I'm missing the easy way to do this.
Thanks!

R2018a

### Kelly Kearney (view profile)

on 19 Jul 2018

I think you should be able to accomplish this by retiming twice; once to fill in any gaps with whatever method you prefer, and the second time to aggregate over each day. If you assume each measurement is representative of a full 10 minutes, then you can simply sum the number of points per day that meet the threshold criteria.
First we build an example timetable with ~10-minute data with some gaps
t = datetime(2018,1,1) + days(0:minutes(10):days(2))';
temp = rand(size(t))*15 - 2;
T = timetable(t, temp);
T = T(rand(size(t))>0.1,:);
Now retime:
dt = minutes(10);
thresh = 0;
T2 = retime(T,'regular', 'linear', 'timestep', dt);
T3 = retime(T2,'daily',@(x) hours(sum(x<thresh)*dt));

Show 1 older comment
Paul Fremeau

### Paul Fremeau (view profile)

on 19 Jul 2018
Okay, final question if you have a second. What if I wanted to count the number of days per month that had at least 6 consecutive hours per day below the threshold temperature?
Kelly Kearney

### Kelly Kearney (view profile)

on 20 Jul 2018
Trying to do run-length calculations in a one-liner gets a bit complicated, so I would write a separate subfunction for that purpose.
T2 = retime(T,'regular', 'linear', 'timestep', dt);
T3 = retime(T2, 'daily', @(x) consectime(x,thresh,dt));
function y = consectime(v, th, dt)
[b,n] = RunLength(v > th);
y = hours(max(n(b==1)) * dt);
end
The T3.temp field now holds the length (in hours) of the longest consecutive period over the threshold, per day. I use the RunLength function from the FEX to do a lot of the heavy lifting here.
Paul Fremeau

### Paul Fremeau (view profile)

on 20 Jul 2018
Very cool, I truly appreciate the help. Best of luck in your endeavors!