# Implementing FIR with MATLAB

There are several ways that MATLAB implements FIR.

• One of them is that convolution function conv directly implements the convolution equation and if the input is a vector of $M$ and impulse response of a filter is a vector of $N$ then the output gives a vector of length $N+M-1$. I have tried it with pen and paper and finally got it (thanks to people here).
• There is another method that uses filter function and in this case the output gives out a vector with size $M$ which is different than the result I was getting with convolution. Apparently in this case MATLAB supplies one output for each input. From what I know from filters is that the output is the input convolved with impulse response.

So what exactly MATLAB is thinking when it spits out one output for one input?

The filter function does exactly what a "real" filter would do: for each input value it computes one output value. The difference with convolution (implemented by conv, with default option 'full' for the shape parameter, cf. the Matlab documentation) is that the tail of the convolution is only computed if as many zeros are appended to the input signal such that the filter's memory is emptied (which is only possible for FIR filters).

Another obvious difference between conv and filter is that filter can implement recursive filters with infinite impulse responses (IIR), unlike conv, which convolves two sequences of finite length.

Here an example to clarify the above:

h = [1 1 1 1];
x = [1 2 3 4];
yc = conv(h,x);
yf = filter(h,1,x);
yf2 = filter(h,1,[x,0,0,0]);
yc =

1    3    6   10    9    7    4
yf =

1    3    6   10
yf2 =

1    3    6   10    9    7    4

• Thank you, but how come input of zero gives three different answers of 9,7, and 4 for yf2 in the above example? – Jack Sep 26 '16 at 14:03
• @Jack: Because that's what's stored in the filter's memory. Do it on a piece of paper and you'll see. – Matt L. Sep 26 '16 at 14:23
• Thank you. So is it correct to conclude that convo and filter functions are doing the same thing and filter function only shows the result for the number of outputs that are equal to the number of inputs? – Jack Sep 26 '16 at 14:27
• @Jack: That's correct for finite length sequences. As mentioned in my answer, filter can do more, because it can implement impulse responses of infinite length by recursion. – Matt L. Sep 26 '16 at 14:34
• If you supply 'same' as input attribute in function 'conv' then output of 'conv' method will be the same what you get from 'filter' method – User1551892 Sep 27 '16 at 6:25