View License

Download apps, toolboxes, and other File Exchange content using Add-On Explorer in MATLAB.

» Watch video

Highlights from
Filter - smooth (calculating the moving average along a vector)

Be the first to rate this file! 6 Downloads (last 30 days) File Size: 1.52 KB File ID: #40758 Version: 1.2
image thumbnail

Filter - smooth (calculating the moving average along a vector)



12 Mar 2013 (Updated )

This function calculates the moving average along that vector. It can be used to smooth a series.

| Watch this File

File Information

 function [vectorout]=moving_average(vectorin,eFave)
  Author: Adri├ín Lara-Quintanilla
  Date: 12/03/2013
  This function calculates a moving average along a vector. "eFave" is the
  number of elements around the element in the input vector "vectorin" used
  to calculate the averaged value in "vectorout". The values at the
  beginning and at the end of "vectorin" that could not be calculated with
  and average of "eFave" elements are calculated as an average of the
  remaining values at the beginning or at the end of "vectorin".
  Note: "eFave" should be an odd number. If not, '1' is added to its value.
  Example: vectorin=[1 2 5 4 8 9] and eFave=4.
  eFave->5, vector out=[x1 x2 4 5.6 x5 x6], note that x3 and x4 can be
  calculated as a mean of the 5 elements (including themselves) around
  them. Because this can not be applied on x1,x2,x5,x6, and the goal is to
  smooth the series, x1=1, x2=mean(1 and 2), x3=mean(8 and 9)
  and x4=9

Required Products MATLAB
MATLAB release MATLAB 8.0 (R2012b)
MATLAB Search Path
Tags for This File   Please login to tag files.
Please login to add a comment or rating.
Comments and Ratings (3)
14 Mar 2013 Heinrich Acker

If you want to know what's fast, use this:

A moving average does not require to use a for loop at all, and the runtime can be almost independent from window size.

Comment only
13 Mar 2013 Adrian Lara-Quintanilla

I really appreciate your comment :), thanks!

Comment only
13 Mar 2013 Jan Simon

Jan Simon (view profile)

Looping over the elements of the vector is very slow for large vectors. Then looping over the elements of the window to be averaged is much faster:
function Y = movemean(X, N)
% X is filtered along 1st dimension
% Window size is 2*N+1
[d1, d2] = size(X);
M = X;
divV = ones(d1, 1);
for i = 1:N
i2 = i + i; % Slightly faster
Z = zeros(i, d2);
M = M + [Z; X(1:d1 - i2, :) + X(1 + i2:d1, :); Z];
divV(i + 1:d1 - i, :) = divV(i + 1:d1 - i, :) + 2;
Y = bsxfun(@rdivide, M, divV);

Comment only
13 Mar 2013 1.1

rewrite title and description

19 Nov 2014 1.2


Contact us