Matlab Tutorial

EE 2370/2170: Design and Analysis of Signals and Systems

Electrical Engineering Department, Southern Methodist University

Prof. Carlos E. Davila

 

The purpose of this tutorial is to give you some hands-on experience with Matlab. To use the tutorial run Matlab on your computer, then read along and type in the Matlab commands that appear in bold face in the Matlab command window. The response which Matlab gives appears directly beneath what you type. By the time you finish this tutorial, you will know how to define Matlab variables, both scalar and arrays, and you will know how to use Matlab to perform simple signal processing tasks like filtering and frequency response. This tutorial is bare-bones, and you should use the help feature to look at more creative ways of using each command.

 

Contents:

 

Defining Variables and Basic Matrix Arithmetic

Defining Large Vectors

Plotting Graphs

M-Files: Writing Matlab Programs

Functions in Matlab (including "quad" and "fplot")

Convolution and Filtering

Saving and Loading Files

Getting Additional Help

 

Defining Variables and Basic Matrix Arithmetic

 

Prior to reading this section, you should be familiar with the rules of matrix arithmetic. You should know how to add vectors and matrices. You should know how to multiply a matrix and a vector, or a matrix and a matrix. First, we'll look at how to define scalar variables. Type in the following:

 

» x = 2 (then press “enter” here)

 

x =

 

     2

 

» y = 3

 

y =

 

     3

 

» z = x + y

 

z =

 

     5

 

not too bad right? Now lets define two vectors

 

» x = [1 2 3]

 

x =

 

     1     2     3

 

» y = [4 5 6]

 

y =

 

     4     5     6

 

type:

 

>> y(1)

 

ans =

 

     4

 

and repeat for y(2) and y(3). Matlab uses the positive integers to index arrays. The first element is y(1), the second element is y(2), etc. zero, or negative numbers are not allowed for array indices. Now compute the sum:

 

» x+y

 

ans =

 

     5     7     9

 

and now compute their inner product:

 

» x*y'

 

ans =

 

    32

 

The answer is 1*4 + 2*5 + 3*6 = 32! Note that y' is the transpose of  y and is a column vector. To check this type:

 

>> y'

 

ans =

 

     4

     5

     6

 

Another way of combining two vectors is doing an element-by-element multiplication:

 

>> x.*y

 

ans =

 

     4    10    18

 

note the period before the multiplication symbol. Now we can define a matrix:

 

» A = [1 2 3

       4 5 6

        7 8 9];

 

Notice the matrix was not echoed since we used the semi-colon. We now multiply A with the transpose of x:

 

 

» A*x'

 

ans =

 

    14

    32

    50

 

Note we had to transpose x in order to properly multiply a matrix and a column vector. Matrices can also be multiplied with one  another:

 

» B = [1 2 3 4

       5 6 7 8

       7 6 5 4];

» A*B

 

ans =

 

    32    32    32    32

    71    74    77    80

   110   116   122   128

 

Now lets try adding A and B:

 

» A+B

??? Error using ==> +

Matrix dimensions must agree.

 

Well, we can’t add a 3 by 3 matrix with a 3 by 4 matrix and Matlab will detect the dimension mismatch and give an error message. Now there are other ways of defining vectors and matrices. For example a zero matrix of dimension 3 rows by 6 columns can be defined as:

 

>> zeros(3,6)

 

ans =

 

     0     0     0     0     0     0

     0     0     0     0     0     0

     0     0     0     0     0     0

 

of course if you add a semicolon ";" after the zeros(3,6), the answer is not printed out. The first number, 3, indicates the number of rows, the second number, 6, is the number of columns. The same can be done with ones:

 

>> ones(3,6)

 

ans =

 

     1     1     1     1     1     1

     1     1     1     1     1     1

     1     1     1     1     1     1

 

Large vectors that consist of a secuence of consecutive numbers can be defined as shown below. Each time you define a new vector, it appears in your workspace. Type "who" to see the variables currently defined in the workspace.

 

Defining Large Vectors

 

A 1 by 100 vector containing samples of a cosine can be generated using

 

>> x = cos(0.1*pi*(0:99));

 

To generate a "ramp" from 1 to 50 try:

 

>> x = [1:1:50];

 

the second number indicates the increment in going from 1 to 50. To generate a "ramp" from 1 to 50 try:

 

>> x = [1:1:50];

 

the second number indicates the increment in going from 1 to 50. When the increment is a "1", you need only specify the first and last numbers of the series:

 

>> x = [1:50];

 

You can also specify what range of values of x are defined:

 

>> x(51:100) = [50:-1:1]

 

This is a useful method of sepecifying "time" values for plotting. For example, suppose the sampling interval in the above example was 1 msec. Then you can define:

 

>> time = [0:0.001:0.099];

 

Plotting Graphs

 

Now type:

 

>> plot(time,x)

>> xlabel('time (msec)')

>> ylabel('x(t)')

 

this will yield the plot:

 

Another way to display plots of sequences or discrete-time signals is using the "stem" command:

 

>> stem(time,x)

>> xlabel('time (msec)')

>> ylabel('x(t)')

 

M-Files: Writing Matlab Programs

 

You can edit a text file containing many Matlab commands. This is done by clicking on the "New M-File" icon in the Matlab toolbar. Try typing in the following program:

 

x(1:52) = [0 0 1:1:50];

x(53:102) = [50:-1:1];

h = [1 2];

for n = 3:101,

   y(n) = 0;

   for m = 1:2,

      y(n) = y(n) + h(m)*x(n-m);

   end

end

plot(y);

 

Save the program as "test.m" in the local directory ("work" or "bin" depending on your version of Matlab) or if you wish, you may change it by entering the desired directory in the "Current Directory" window in the Matlab toolbar. Now try running the program, by typing:

 

>> test

 

Note the presence of two nested "for" commands. Matlab has all of the standard programming structures ("for", "while", "if"). Type

 

>> help while

 

for syntax information.

 

Functions in Matlab

 

Matlab also enables one to write user-defined functions. Edit the following function in a new edit window:

 

function y = x2(t)

y = t^2;

 

save the M-file as "x2.m" then from the Matlab prompt type

>> x2(3)

 

ans =

 

     9

 

the function returns the square of the argument. Some built-in Matlab functions like "fplot" and "quad" require that the function return a vector if the parameter passed to it is also a vector. Clearly this is not the case for x2.m. So x2.m must be modified as:

 

function y = x2(t)

for k = 1:length(t)

    y(k) = t(k)^2;

end

 

note that this modified function still works for scalar values of "t", however now you can type:

 

>> x2([1 2 3 4])

 

ans =

 

     1     4     9    16

 

Read the help files for "fplot" and type:

 

>> fplot(@x2, [0 2])

 

you should get:

Now read the help file for "quad", a built-in Matlab function that numerically computes integrals. The syntax for its use is

>> quad(@fun,a, b, tol)

 

where "fun" is the function to be integrated, a and b are the limits of integration, and tol is a tolerance used to determine how accurate the integral is computed. Type

 

>> quad(@x2, 0, 1, 1e-10)

 

ans =

 

    0.3333

 

Convolution and Filtering

 

Now let’s look at some signal processing stuff that you can do with Matlab. Suppose that we want to filter the discrete-time signal, x[n] = {2, 3, 5, 1, 6, 3} with an FIR filter with coefficients h[n] = {2,  –1, 1}. There are several ways of doing this. One way is to convolve them directly with the “conv” function:

 

» h = [2 -1 2];

» x = [2, 3, 5, 1, 6, 3];

» y = conv(x,h)

 

y =

 

     4     4    11     3    21     2     9     6

 

Notice that you should insert either spaces or commas between successive array entries. Another way of filtering is with the “filter” command:

 

» y = filter(h,1,x)

 

y =

 

     4     4    11     3    21     2

 

Notice that “filter” truncates the filter output so it has the same length as the input. Suppose we have the difference equation:

 

y[n] = x[n] + 0.9y[n-1]                                     (1)

 

and we want to determine the impulse response of this filter out to 100 points. We first must note that  (1) can be written as

 

y[n] – 0.9y[n-1] = x[n]                                     (2)

 

taking the Z transform gives:

 

Y(z) (1 – 0.9z-1) = X(z)                                    (3)

 

or H(z) = Y(z)/X(z) = 1/((1 – 0.9z-1) = B(z)/A(z). The “filter” command expects the coefficients of B(z) and A(z) to appear within the “b” and “a” vectors, respectively. So we simply type:

 

» b = 1;

» a = [1 -0.9];

» x = [1 zeros(1,99)];

» y=filter(b,a,x);

 

Now lets try plotting the result from the previous filter command:

 

» plot(y)

 


The resulting impulse response now appears in the plot as:

 


 

 

The input, x = {1, 0, 0, ...} was defined using the zeros (99,1), which pads the vector with 99 zeros after the one. Now suppose we define the following digital filter:

 

y[n] = 0.1x[n] + .5x[n-1] – 0.8x[n-2] + 0.3y[n-1] – 0.5y[n-2]

 

The corresponding a and b vectors are:

 

» a = [1 0.9 0.5];

» b = [0.1 0.5 -0.8];

 

Suppose we would like to filter the signal x[n] = cos(0.7pn), n = 0, 100. The signal x[n] can be defined on one line by typing:

 

» x = cos(0.7*pi*(0:99));

 

which produces a 1 by 100 array. Now lets filter and plot:

 

» y=filter(b,a,x);

» plot(x)

» hold on

» plot(y,'r')

 

The “hold on” allows us to plot two signals on the same plot. The second “plot” command also makes the plot for the filter output y appear in red.

 


 

 

 


Notice that the output is attenuated with respect to the input. It also has undergone a slight phase shift. So apparently at the relatively low frequency of 0.3p, the filter attenuates. If you wanted to print out this plot, you can type:

 

» print -Pch_si

 

or indicate whatever printer you would like to print on after the “-P”. We can determine the frequency response of the filter using the “freqz” command.

 

Saving and Loading Files

 

Sometimes it may be useful to load a Matlab data file (*.mat) or to save either certain Matlab variables or the entire workspace. To load a data file, simply type

 

>> load HW3_dat.mat

 

(the .mat can be ommitted). If the file "HW3_dat.mat" is present in the local directory then it will be loaded into Matlab. To save variables use the "save" command.

 

>> save y y

 

saves the variable "y" into a file names "y". You can also save the entire workspace (all current variables) by typing:

 

>> save workspace

 

where "workspace" can be any file name you choose.

 

Getting Additional Help

 

With this as with other topics discussed in this tutorial, there is extensive online help. Type

 

>> help <command>

 

or simply

 

>> help

 

to get a list of things for which help is available.