How to implement a filter in matlab I want to implement the 'filter' function in matlab but I just can't seem to replicate the results I get when using the matlab function.

My understanding of the matlab function is that it takes 3 arguments: 'b' = array of numerator coefficients , 'a' = array of denominator coefficients and 'array' = the array to be filtered.So if you wanted to filter an array with a filter H(z) where:

$$
  H(z) = \frac{b_1 + b_2z^{-1}}{a_1 + a_2z^{-1}}
$$

and store it in an array called "result" then you would write

result = filter( [b1 b2] , [a1 a2] , array );


Now I tried to implement the 'filter' function ( with the number of coefficients in the numerator and denominator limited to 2) by getting the difference equation from H(z) then using it to get the resultant array but this route does not seem to work, ie

$$
  H(z) = \frac{Y(z)}{X(z)} = \frac{b_1 + b_2z^{-1}}{a_1 + a_2z^{-1}}
$$

$$
  X(z) (b_1 + b_2z^{-1}) = Y(z)(a_1 + a_2z^{-1})
$$

$$
b_1x[n] + b_2x[n-1] = a_1y[n] + a_2y[n-1]
$$

$$
\implies y[n] = \frac{b_1}{a_1}x[n] + \frac{b_2}{a_1}x[n-1] - \frac{a_2}{a_1}y[n-1] 
$$

Meaning the matlab code should look something like

function [ result ] = myFilter( b , a , audio )
%MyFilter
%a,b = Two Element Arrays
%array = the array we want to filter

N = size(audio,2);

for i = 1:N
   if( i == 1 )
       result(i) = ( b(2)/a(1)) * audio(i);

   else
       result(i) = ( b(1) / a(1) ) * audio(i) + ...
                   ( b(2) / a(1) ) * audio(i-1) - ...
                   ( a(2) / a(1) ) * result(i-1);
   end
end

end


The function above does not produce the same results as the matlab filter function.Does anyone know what I am doing wrong? Have I understood how the filter function in matlab works?
You have a typo in:

result(i) = ( b(2)/a(1)) * audio(i);


That should be:

result(i) = ( b(1)/a(1)) * audio(i);