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

前端 未结 6 1277
小鲜肉
小鲜肉 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 20:57

    You could try and create a cell array and apply mean and std via cellfun. It's ~10% slower than your solution for 900 entries, but ~10x faster for 90000 entries.

    [t,sortIdx]=sort(t); %# we only need to sort in case t is not monotonously increasing
    x = x(sortIdx);
    
    tIdx = floor(t/60); %# convert seconds to minutes - can also convert to 5 mins by dividing by 300
    tIdx = tIdx - min(tIdx) + 1; %# tIdx now is a vector of indices - i.e. it starts at 1, and should go like your iteration variable.
    
    %# the next few commands are to count how many 1's 2's 3's etc are in tIdx
    dt = [tIdx(2:end)-tIdx(1:end-1);1]; 
    stepIdx = [0;find(dt>0)];
    nIdx = stepIdx(2:end) - stepIdx(1:end-1); %# number of times each index appears
    
    %# convert to cell array
    xCell = mat2cell(x,nIdx,1);
    
    %# use cellfun to calculate the mean and sd
    mu(tIdx(stepIdx+1)) = cellfun(@mean,xCell); %# the indexing is like that since there may be missing steps
    sd(tIdx(stepIdx+1)) = cellfun(@mean,xCell);
    

    Note: my solution does not give the exact same results as yours, since you skip a few time values at the end (1:60:90 is [1,61]), and since the start of the interval is not exactly the same.

提交回复
热议问题