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')
yM
in the code, so all information is there, just not in a greatly reader-friendly form. I think that despite all its weaknesses the question shouldn't be closed because it shows an important aspect of the commonly used Matlab functionfilter
, namely that it's not correct to supply $y[-1]$ etc. as initial states. $\endgroup$ – Matt L. Apr 30 '19 at 8:40