MATLAB Programming/Filtering

From testwiki
Revision as of 18:21, 17 July 2007 by imported>Herbythyme (Revert to revision 775371 dated 2007-03-05 19:03:18 by 130.88.178.71 using popups)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

Filtering is a broad subject. For the MATlab wiki I will focus on how to implement filters. For more on the theory of filtering the reader should reference the Digital Signal Processing wiki book.


The Moving Average Filter

Formula:

y[n]=1hp=0h1x[np]

MATlab implementation(All the code here was intended to be put in an M-file):

clc;
clear;

v=.01
f=100;
fs=5000;
t=0:1/fs:.03
x=sin(2*pi*f*t);                             %original signal

r=sqrt(v)*randn(1,length(t));                %noise
Xw=x+r;                                      %signal plus noise (filter input)
                                             % I have choosen h=3 
for n= 3:length(Xw),
   y(n)=(Xw(n)+(Xw(n-1))+(Xw(n-2)))/3;       %y[n] is the filtered signal
end

plot(y);
hold;
 
plot(x,'r');                                 %plot the original signal over top the  
                                             %filtered signal to see the difference

The moving average filter is simple and effective. One of the things that is a problem is the lag associated with the moving average filter. The more samples used the longer the lag experienced(All filters have lag). How much lag can be tolerated is up to the individual.

The Alpha Beta filter

The Kalman Filter

The Kalman filter is a recursive method of combining to estimates to determine the truth. A few parameters that are widly used are the initial conditions or current value and measured data.

Equation:


Example:

n=100;
sigma=(20/6076);
R=100;
Rm=R+sigma*randn;
Rs(1)=Rm(1);
Cs=sigma^2

for i=2:n
   Rm(i)=R+sigma*randn;
   alpha=Cs/(Cs+sigma^2);
   Rs(i)=Rs(i-1)+alpha*(Rm(i)-Rs(i-1));
   Cs=(1-alpha)*Cs;
end

All this code does is take a constant value R and adds noise to it. Then it filters the new signal in an effort to separate the noise from the original signal.