Matlab filter function filter (B, A, x).

3,150 views
Skip to first unread message

Fernando Negrão

unread,
May 29, 2014, 10:34:38 PM5/29/14
to fre...@googlegroups.com

Can someone help me? I'm a Freemat new user and I need to use the "filter" function of Matlab for DSP classes. Here is how it works:


Matlab's filter function

  • The Matlab implementation for the filter is most easily accomplished using the filter function
    y = filter(B, A, x).
    

  • The filter function takes three (3) arguments:
    1. feedforward coefficients B,
    2. feedback coefficients A,
    3. and the input signal $ x$.

  • If the filter doesn't have feedback coefficients, as is the case with an FIR filter, A = 1.

  • Our simple low-pass filter, $ y(n) = x(n)+x(n-1)$, is a first order filter with 2 feedforward coefficients (B = [1, 1]).

  • In matlab:
    B = [1 1];
    A = 1;
    y = filter(B, A, x)
 Thank you. 

Jonathan Weaver

unread,
Jun 11, 2014, 11:16:00 AM6/11/14
to fre...@googlegroups.com
I've been implementing FIR filters with the conv function for a while.  I've thought IIR filters would be nice to implement, but I haven't had a need.  Your post gave me incentive to write an implementation of the filter function so I could use FIR and IIR filters.  I pasted the contents of the m-file below.  It appears to work.  Enjoy!

% FILTER - Implements a 1-D Digital Filter

%

% USAGE

%

% y = filter(b,a,X) filters the data in vector X with the filter described by

% numerator coefficient vector b and denominator coefficient vector a. If a(1)

% is not equal to 1, filter normalizes the filter coefficients by a(1). If a(1)

% equals 0, filter returns an error.

%

% This is a subset of the functionality of the MATLAB filter. It only handles

% X as a vector.

%

% Date: 6/11/2014

% Version: v1.0

% Licensed under the GPL

% Copyright (C) 2014 Jonathan Weaver <jonw...@aim.com>


function y = filter(b,a,X)


% This file is free software: you can redistribute it and/or modify

% it under the terms of the GNU General Public License as published by

% the Free Software Foundation, either version 3 of the License, or

% (at your option) any later version.

%

% This program is distributed in the hope that it will be useful,

% but WITHOUT ANY WARRANTY; without even the implied warranty of

% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the

% GNU General Public License for more details.

%

% You should have received a copy of the GNU General Public License

% along with this program. If not, see <http://www.gnu.org/licenses/>.


y = conv(b,x);

y = y(1:length(x));

ap = [0 -1*a(2:end)];

a1 = a(1);

if a1 == 0

error('a(1) must be nonzero');

end

ya = y;

for n = 1:(length(x))

ya = conv(ya,ap);

ya = ya(1:length(x));

y = ya + y;

end

y = y ./ a1;

end




Reply all
Reply to author
Forward
0 new messages