function with moving average on matlab

1k Views Asked by At

Do a function that maintains moving average, the function gives the average of all the numbers that have been put in the function.

does anyone know how to do this ?

2

There are 2 best solutions below

0
On

If list is an array of numbers of the form [a,b,c,...,z] then we can simply take

average = sum(list)/length(list)

If you prefer not to have numbers entered as an array, you can do this:

function y = average(varargin)

    list = cell2mat(varargin);
    y = sum(list)/length(list);
0
On

Moving average of n points: use conv:

data = [1 2 4 6 8 11 5];
n = 3;
result = conv(data, repmat(1/n, [1 n]), 'valid');

Cumulative average from the beginning to current position: use cumsum:

result = cumsum(data)./(1:numel(data));