MATLAB: compute mean of each 1-minute interval of a time-series

前端 未结 6 1270
小鲜肉
小鲜肉 2020-12-09 20:16

I have a bunch of times-series each described by two components, a timestamp vector (in seconds), and a vector of values measured. The time vector is non-uniform (i.e. sampl

6条回答
  •  离开以前
    2020-12-09 21:04

    Disclaimer: I worked this out on paper, but haven't yet had the opportunity to check it "in silico"...

    You may be able to avoid loops or using cell arrays by doing some tricky cumulative sums, indexing, and calculating the means and standard deviations yourself. Here's some code that I believe will work, although I am unsure how it stacks up speed-wise to the other solutions:

    [t,sortIndex] = sort(t);  %# Sort the time points
    x = x(sortIndex);         %# Sort the data values
    interval = 60;            %# Interval size, in seconds
    
    intervalIndex = floor((t-t(1))./interval)+1;  %# Collect t into intervals
    nIntervals = max(intervalIndex);              %# The number of intervals
    mu = zeros(nIntervals,1);                     %# Preallocate mu
    sd = zeros(nIntervals,1);                     %# Preallocate sd
    
    sumIndex = [find(diff(intervalIndex)) ...
                numel(intervalIndex)];  %# Find indices of the interval ends
    n = diff([0 sumIndex]);             %# Number of samples per interval
    xSum = cumsum(x);                   %# Cumulative sum of x
    xSum = diff([0 xSum(sumIndex)]);    %# Sum per interval
    xxSum = cumsum(x.^2);               %# Cumulative sum of x^2
    xxSum = diff([0 xxSum(sumIndex)]);  %# Squared sum per interval
    
    intervalIndex = intervalIndex(sumIndex);  %# Find index into mu and sd
    mu(intervalIndex) = xSum./n;                             %# Compute mean
    sd(intervalIndex) = sqrt((xxSum-xSum.*xSum./n)./(n-1));  %# Compute std dev
    

    The above computes the standard deviation using the simplification of the formula found on this Wikipedia page.

提交回复
热议问题