Difference equations: lecture examples

Mathematica definitions

Load needed packages for this notebook

<< Graphics`Colors`;
<< Miscellaneous`Audio`;

Set up defaults

Turn off annoying warning messages

Off[General::spell];
Off[General::spell1];

Set default options for specific functions

SetOptions[Plot, Frame -> True];
SetOptions[ListPlot, Frame -> True,  PlotJoined -> True,  
        Axes -> {True, False}];
SetOptions[Fourier, 
        FourierParameters -> {1, -1}];
SetOptions[InverseFourier, 
        FourierParameters -> {1, -1}];

Visualization functions

Fix time variable for sampled signals

FixTime[signal_, 
          sampleRate_] := 
Module[{time, 
            data}, 
time = 
            Table[i/sampleRate, {i, 1, 
                Length[signal]}]; 
data  =  {time, 
                signal} // Transpose
];

Plot discrete-time signal as sequence of amplitude lines

DiscreteListPlot[signal_, color_:  Black, 
          opts___] := 
Module[{data, g1, 
            g2}, 
If[
            Length[signal[[1]]]  ==  2, 
data = 
              signal, 
data = 
              FixTime[signal, 
                1]
]; 
g1 = Line[{{#[[1]], 0}, {#[[1]], #[[2]]}}] &  /@  
              data; 
g2 = {PointSize[ .015], 
                  Point[#]} &  /@  data; 
Show[
            Graphics[{color, g1, g2}], 
            opts]
];

Example #1: non-recursive difference equation

Finite length, discrete-time sequence

signal  =  {1, 4, 3, 5, 4, 2, 3};

x[n_] := 
If[
          n ≤ 0 || 
            n > Length[
                signal], 
0, 
signal[[n]]
];

Definition of difference equation

y[n_] := x[n]^2  +  x[n - 1];

Example evaluations

x[1]

y[3]

Input sequence plot

DiscreteListPlot[Table[{n, x[n]}, {n, 0, 10}],  Red,  
        Frame -> True,  Axes -> {True, False}];

Output sequence plot

DiscreteListPlot[Table[{n, y[n]}, {n, 0, 10}],  Blue,  
        Frame -> True,  Axes -> {True, False},  
        PlotRange -> All];

Example #2: recursive difference equation

Finite length, discrete-time sequence

signal  =  {1, 4, 3, 5, 4, 2, 3};

x[n_] := 
If[
          n ≤ 0 || 
            n > Length[
                signal], 
0, 
signal[[n]]
];

Definition of difference equation

Initial condition

y[-1] = 0;

Difference equation

y[n_] := -1/2  y[n - 1]  -  x[n];

Input sequence plot

DiscreteListPlot[Table[{n, x[n]}, {n, 0, 20}],  Red,  
        Frame -> True,  Axes -> {True, False}];

Output sequence plot

DiscreteListPlot[Table[{n, y[n]}, {n, 0, 20}],  Blue,  
        Frame -> True,  Axes -> {True, False},  
        PlotRange -> All];