Search All of the Math Forum:

Views expressed in these public forums are not endorsed by NCTM or The Math Forum.

Notice: We are no longer accepting new posts, but the forums will continue to be readable.

Topic: Coding Matlab function "filter" in C++
Replies: 6   Last Post: Feb 11, 2013 11:03 AM

 Messages: [ Previous | Next ]
 Peter Boettcher Posts: 3,594 Registered: 12/4/04
Re: Coding Matlab function "filter" in C++
Posted: Nov 29, 2005 6:37 PM

"Chris Heier" <enygma@gmail.com> writes:

> I'm working on a fairly simple Matlab script but am having troubles
> trying to figure out what is really happening behind the scenes. I'm
> working with an API for in house software to play with seismic data. I
> was given a template from one of the developers to work with to develop
> our own filter.
>
> The main command that has me stumped pretty much is "y = filter(b, a,
> x)" where X is a full trace of a variable length (depending on the
> value contained in NSamples in C++).
>
> a = [1 k1*(1+k2) k2]
> and
> b = [k2 k1*(1 + k2) 1]
>
> What is happening in the filter command eludes me and I'm having
> troubles trying to figure out how to work with it in C++ without having
> to try and include a Matlab library in the template. The documetnation
> on "filter" is somewhat helpful, but I'm having troubles trying to get
> my head around it, so I guess what I'm looking for is mainly an
> explanation as to what "filter" is doing with the information given.

The docs for filter pretty much tell it all:

a(1)*y(n) = b(1)*x(n) + b(2)*x(n-1) + ... + b(nb+1)*x(n-nb)
- a(2)*y(n-1) - ... - a(na+1)*y(n-na)

Substituting:
y(n) = k2*x(n) + k1*(1+k2)*x(n-1) + x(n-2) - k1*(1+k2)*y(n-1) - k2*y(n-2)

x is the input, y is the output.

x(n) is current input sample, x(n-1) is the first previous input
sample, etc.

Notice that the equation relies on previous values of the output y as
well (this is what makes this particular filter an IIR filter,
infinite impulse response). Just store those two previous value of
the output as you iterate down the array. y_prev_1 and y_prev_2 or
something.

The rest is almost C code already.

--
Peter Boettcher <boettcher@ll.mit.edu>
MIT Lincoln Laboratory
MATLAB FAQ: http://www.mit.edu/~pwb/cssm/

Date Subject Author
11/29/05 Chris Heier
11/29/05 Peter Boettcher
11/30/05 Chris Heier
11/30/05 Peter Boettcher
11/30/05 Chris Heier
2/5/13 Hossein
2/11/13 Jan Simon