MATLAB Answers

Rica

IIR filter as amoving averege

Asked by Rica
on 22 Mar 2013

hi! I want to use the filter function as a moving averege filter. the Type of the filter should be IIR Filter. Te window length is 3. for exemple:

 %
X=rand(1:300)
B=1/3
A=1-B;
Y=filter(B,A,X)->First order IIR filter

the filter functi should start after reaching the window lenght. for the first 2 value (before reaching the window lenght of 3) , i wan to calculate just the mean value.

 %
Y(1)=X(1)
Y(2)=mean(Y(1)+X(2));
Y(3:end)=filter(B,A,X(3:end))

could someone help me ?

thank you

  0 Comments

Products

No products are associated with this question.

2 Answers

Answer by Andrei Bobrov
on 22 Mar 2013
Edited by Andrei Bobrov
on 22 Mar 2013
 Accepted answer

EDIT

out = filter([1 1 1]/3, 1, x(:));
out(1:2) = [x(1);sum(x(1:2))/2];

  1 Comment

Andrei Bobrov
on 22 Mar 2013

EDIT


Answer by Image Analyst
on 22 Mar 2013
Edited by Image Analyst
on 22 Mar 2013

To get the middle chunk, do this:

yMiddle = conv(x, [1 1 1]/3, 'valid');

Then prepend and append the endpoints as you already calculated.

Edit: Haven't heard from you, so here's a full-blown demo for you. It shrinks the window as it gets closer to the edges. Let me know if you need a version robust enough to handle any window size.

    x = 1:10
    % Get the first and last elements.
    yFirst = mean(x(1:2))
    yLast = mean(x(end-1:end))
    % Now get the middle with a moving average.
    yMiddle = conv(x, [1 1 1]/3, 'valid')
    yFinal = [yFirst yMiddle, yLast]

In the command window you see:

x =
     1     2     3     4     5     6     7     8     9    10
yFirst =
    1.5000
yLast =
    9.5000
yMiddle =
    2.0000    3.0000    4.0000    5.0000    6.0000    7.0000    8.0000    9.0000
yFinal =
    1.5000    2.0000    3.0000    4.0000    5.0000    6.0000    7.0000    8.0000    9.0000    9.5000

  0 Comments


Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply today