Jonas
Jonas

Reputation: 318

Average and synchronize a timeseries with varying timestamps to a user-defined interval in MATLAB

Assume the following timeseries (ts) with assigned values:

time    val
15:00   4
15:45   7
17:12   2.3
17:50   2.9

Every value from a timestamp is valid until the next appears. Thus, from 15:00 to 15:45 the value is 4 or from 15:45 to 17:12 it is 2.3. Every new data point between these timestamps should have the same value. What i want is a new ts, with a constant time-interval and a pre-defined start point. Let's say the starting point is 15:00 and the interval should be 30 min. Normally, I could use the synchronize function - however, the function uses the interpolation method and this is not what i need here, since the values between the data points should not be interpolated, but be averaged if timestamps are overlapping.

The new ts should be like:

time   val
15:00  4
15:30  5.5
16:00  7
16:30  7
17:00  4.18

The value for timestamp 15:30 is computed as = (4*15+7*15)/30, and so on. I have implemented a code, that is capable of fixing this by applying the trapz function with a lot of if statements. However, I was wondering if there are better/simpler solutions around, as a modified synchronize function, since I have more than 500.000 data points.

Thanks in advance

Upvotes: 1

Views: 412

Answers (1)

Jonas
Jonas

Reputation: 318

I managed to fix my problem by dividing all time steps into minute-values and afterwards applying the trapezoidal rule to get the sum of the area under the curve (AUC) and then the average by dividing with the applied minute interval.

    AllValues = interp1(Time,Data,NewTime,'previous')';
    [Xdata,Ydata] = stairs(NewTime,AllValues);
    NewTS = timeseries(Xdata,Ydata);
    TrapzSum =  cumtrapz(NewTS.time,NewTS.data);
    TrapzSum =  TrapzSum(1:2:end); 
    NewResults = diff(TrapzSum(IndicesOfNewInterval))/MinInt;

Upvotes: 1

Related Questions