Using Matlab's filter() function for solving difference equation with initial conditions I am trying to solve a difference equation with initial conditions using Matlab's filter function:

$$y[n]=\frac12y[n-1]+x[n],\qquad y[-1]=1\tag{1}$$

For $x[n]=6u[n]$, calculation of $y[n]$ by hand gives

$$y[n]=\left[12-(6-y[-1]/2)\left(\frac12\right)^n\right]u[n]\tag{2}$$

However, the solution produced by filter is different. Could anybody point out my mistake?

The code is shown below:

disp('Solution of a difference equation:')
% The example difference equation considered is
% y(n) = 0.5y(n-1) + x(n) 
num_coef = [ 1 ]; % coefficient of x
den_coef = [1 -0.5]; % coefficient of y
n = 0:4; % Considering five samples 
x = 6 * ones(1,5) % x(n) = 6u(n)
init_cond = [1];  % y(-1) = 1
y = filter(num_coef, den_coef, x, init_cond) % Solution returned by 'filter'
yM = 12 - (11/2)*(1/2).^n % Solution obtained manually
plot(y);hold on; % PLots for comparison
plot(yM,'r')
The problem is the definition of the initial condition of the function filter(). Note that according to the mathworks reference page, filter is implemented using a direct-form II transposed structure. If you look at the corresponding diagram, you see that the filter states (called $w_k(m)$ in the figure) are defined after multiplication with the respective filter coefficients.

So in your example if you want to initialize filter with some past output value $y[-1]$, your initial state is given by $y[-1]\cdot 0.5$ because that's the value of the input of the delay element.

y = filter(num_coef, den_coef, x, 0.5)

should give you the expected result.

Note that for the general case there's the function filtic, which computes the necessary initial conditions given past output samples (and, if necessary, past input samples). For your example you would use the command

zi = filtic(num_coef, den_coef, 1)

which results in zi = 0.5, as explained above.