How can I (efficiently) compute a moving average of a vector?

前端 未结 3 875
忘了有多久
忘了有多久 2020-12-15 00:44

I\'ve got a vector and I want to calculate the moving average of it (using a window of width 5).

For instance, if the vector in question is [1,2,3,4,5,6,7,8]

3条回答
  •  别那么骄傲
    2020-12-15 01:30

    Another possibility is to use cumsum. This approach probably requires fewer operations than conv does:

    x = 1:8
    n = 5;
    cs = cumsum(x);
    result = cs(n:end) - [0 cs(1:end-n)];
    

    To save a little time, you can replace the last line by

    %// clear result
    result(1,numel(x)-n+1) = 0; %// hackish way to preallocate result
    result(1) = cs(n);
    result(2:end) = cs(n+1:end) - cs(1:end-n);
    

提交回复
热议问题