EE342.01: MATLAB M-FILE FOR RECURSIVELY SOLVING A DIFFERENCE EQUATION

MATLAB M-File example4.m:
%
%  Filename:  example4.m
%
%  Description:  This m-file demonstrates how a difference
%                equation can be recursively solved.
%

N = 10;                      % maximum n for recursion
yprev = 0;                   % initial y value, y[-1] = 0

for n=0:N,                   % recursion loop
  
  if (n == 0)                % x[n] = 2delta[n]
    x = 2;
  else
    x = 0;
  end
  
  y = x + 0.5*yprev;         % compute y[n]
  yprev = y;                 % store current y value for next interation
  
  nvec(n+1) = n;             % store n and y into vectors for plotting
  yvec(n+1) = y;
  
end;

n_and_y = [nvec' yvec']      % view n and y

stem(nvec, yvec);            % plot y vs n
xlabel('n');                 % label plot
ylabel('y[n]');
title('EE342.01: Plot of y[n] from Recursion');
MATLAB Output Generated:
n_and_y =

         0    2.0000
    1.0000    1.0000
    2.0000    0.5000
    3.0000    0.2500
    4.0000    0.1250
    5.0000    0.0625
    6.0000    0.0312
    7.0000    0.0156
    8.0000    0.0078
    9.0000    0.0039
   10.0000    0.0020
MATLAB Plot Generated: