Aim of the experiment
This experiment will introduce you to the basics of working with Matlab.
You will perform some elementary operations, obtain numerical results and plot figures.
- Using M-files in Matlab
- Getting help in Matlab
- Further tutorials
Note: Non-standard Matlab commands are highlighted in green.
Ensure that you have a valid user account on the Department's computer system and that you can log in.
Read through these instructions.
Matlab is an interactive program for numerical computation and data visualisation; it is used extensively by engineers for analysis and design.
There are many different toolboxes available that extend the basic functions of
Matlab into different application areas; in the further tutorials, extensive use is made of the Control Systems Toolbox.
Matlab is supported on Unix, Macintosh and Windows environments; a student version of Matlab is available for personal computers.
For more information on Matlab, see the Mathworks web site.
The idea behind this tutorial is that you can view it in one window while running Matlab
You should be able to re-do all of the plots and calculations in the tutorials by cutting and pasting text from the tutorials into Matlab or a script file (a.k.a. an m-file).
Assessment: in tackling the exercises, you should save all your routines.
A demonstrator will come around at the end of the session to mark them.
Let's begin by creating something simple, a vector.
Enter each element of the vector (separated by a space) between brackets, and set it equal to a value.
For example, to create the vector a, enter into the Matlab command window (you can
"copy" and "paste" from your browser into Matlab to make it easy):
Matlab should return:
Let's say you want to create a vector with elements between 0 and 20 evenly spaced in increments of 2 (this method is frequently used to create a time vector):
t = 0:2:20
0 2 4 6 8 10 12 14 16 18 20
Manipulating vectors is almost as easy as creating them.
First, suppose you would like to add 2 to each of the elements in vector a.
The formula for this is:
b = a + 2
3 4 5 6 7 8 11 10 9
Now, suppose you would like to add two vectors together.
If the two vectors are the same length, it is easy.
Simply add them, as shown:
c = a + b
4 6 8 10 12 14 20 18 16
Subtraction of vectors of the same length works exactly the same way.
To make life easier, Matlab includes many standard functions.
Each function is a block of code that accomplishes a specific task.
Matlab contains all of the standard functions, such as sin, cos, log, exp, sqrt, as well as many others.
Commonly used constants
such as pi (π), and i or j for the square root of -1, are also incorporated
into Matlab, e.g.:
To find out how to use any function, type help [function name] at the Matlab command window.
Matlab even allows you to write your own functions with the function command; follow the link
to learn how to write your own functions and see a listing of the functions created for this tutorial.
It is also easy to create plots in Matlab.
Suppose you wanted to plot a sine wave as a function of time.
First make a time vector (the semicolon after each statement tells Matlab we
don't want to see all the values) and then compute its sine at each time.
The plot contains approximately one period of a sine wave.
Basic plotting is very easy in Matlab, and the plot command has extensive add-on capabilities.
For example, you can easily label the axes, add a title or legend with the commands
xlabel, ylabel, title, and legend.
I would recommend you visit the plotting page to learn more about it or try the help.
y = sin(t);
In Matlab, a polynomial is represented by a vector.
To create a polynomial in Matlab, simply enter each coefficient of the polynomial into
the vector in descending order.
For instance, let's say you have the following polynomial:
To load this in Matlab's workspace, just enter it as a vector:
x = [1 3 -15 -2 9]
1 3 -15 -2 9
Matlab can interpret a vector of length n+1 as an nth order polynomial.
So, if your polynomial is missing any coefficients, you must enter zeros in the appropriate place in the vector.
would be represented in Matlab as:
You can find the value of a polynomial using the polyval function.
For example, to evaluate the above polynomial at s=2, type
z = polyval([1 0 0 0 1],2)
You can also extract the roots of a polynomial, which is especially useful when you have a high-order polynomial, such as
Finding the roots is simply a matter of entering the command
roots([1 3 -15 -2 9])
Now, let's say you wanted to multiply two polynomials together.
The product of two polynomials is found by taking the convolution of their coefficients.
Matlab's function conv will do this for you.
x = [1 2];
y = [1 4 8];
z = conv(x,y)
1 6 16 16
Dividing two polynomials is just as easy.
The deconv function will return the remainder as well as the result.
Let's divide z by y and see if we get x:
[xx, R] = deconv(z,y)
0 0 0 0
As you can see, this is just the polynomial vector x from before.
If y had not gone into z evenly, the remainder vector would have been something other than zero.
If you want to add two polynomials together which have the same order, a straightforward z=x+y will work (the vectors x and y must have the same length).
In the general case, the user-defined function polyadd can be used.
To do so, copy the polyadd function into an m-file, making sure you store it somewhere on your path, and then use it just as you would any Matlab function.
Once you've done this, you can add two uneven polynomials, x and y:
z = polyadd(x,y)
1 4 8
1 5 10
Entering matrices into Matlab is similar to entering a vector, except each row of elements is separated by a semicolon ; or a carriage return <enter>:
B = [1 2 3 4;5 6 7 8;9 10 11 12]
1 2 3 4
5 6 7 8
9 10 11 12
B = [ 1 2 3 4
5 6 7 8
9 10 11 12]
1 2 3 4
5 6 7 8
9 10 11 12
Matrices in Matlab can be manipulated in many ways.
For one, you can transpose a matrix using the apostrophe ' (or prime):
C = B'
1 5 9
2 6 10
3 7 11
4 8 12
The apostrophe on its own actually gives the complex conjugate transpose (i.e., it changes the sign of all imaginary parts at the same time as transposing the matrix).
If C had been complex, the apostrophe would have given complex conjugate values for the transpose.
To get the regular transpose, use .', but in the above case the two commands are the same (because all the values in C are real numbers, i.e., the matix is not complex).
You can multiply the two matrices B and C together.
Remember that the order matters when multiplying matrices (and the number of columns in the first matrix must match the number of rows in the second):
D = B * C
30 70 110
70 174 278
110 278 446
D = C * B
107 122 137 152
122 140 158 176
137 158 179 200
152 176 200 224
Another option for matrix manipulation is that you can multiply the corresponding elements of two matrices, one by one, using the .* operator.
The matrices must be the same size to do this:
E = [1 2;3 4]
F = [2 3;4 5]
G = E .* F
If you have a square matrix, like E, you can multiply it by itself.
You can do this as many times as you like, which is the same as raising it to a given power:
In order to cube each element in the matrix, just raise to the power of three element-by-element:
To find the inverse of a (square) matrix:
X = inv(E)
or its eigenvalues:
There is a function that finds the coefficients of the characteristic polynomial of a matrix.
The poly function creates a vector that includes these coefficients:
p = poly(E)
1.0000 -5.0000 -2.0000
Remember that the eigenvalues of a matrix are the same as the roots of its
To print a plot or an m-file, just click on the figure window or editor, select Print under the File menu, and hit return.
Alternatively, if you want to save the plot and print it later (for example to include in a technical report), you can use the print command in Matlab to generate a file.
See the help (help print) to discover all the options, which include postscript (PS/EPS), JPEG, TIFF and PDF, e.g.:
print -dps fig1.ps
Sometime later, you could print the plot using the command "lpr -P<printername> fig1.ps" from a terminal window (e.g., an x-windows terminal or a command window on the linux desktop).
Using M-files in Matlab
You can either type commands directly into matlab, or put all of the commands that you will need together in an m-file, and just run them as a script.
You can do this most simply using the Matlab editor.
It has some extra features for running and debugging your code, but it is equivalent to using any text editor to write and save files ending in .m.
If you put all of your m-files in the same directory that you run matlab from, then matlab will always find them.
Alternatively, you can ensure that the directory where you store your m-files is on the Matlab path, and it will find them there.
You can insert comments by putting % at te beginning of the line.
Getting help in Matlab
Matlab has pretty good on-line help nowadays, which has an index and is searchable.
As has already been mentioned a couple of times, you can access it from the command line too by typing
which will give you more information on that command.
It helps therefoer if you know the name of the command that you are looking for!
Matlab allows you to see what there is, if you just enter help; then you can navigate through the toolboxes.
A list of the all the ones used in these tutorials is given in the command listing.
Here are a few tips to end this tutorial.
You can get the value of a particular variable at any time by typing its
1 2 3
4 5 6
7 8 9
You can also have more that one statement on a single line, so long as you
separate them with either a semicolon or comma.
You may have noticed that, so long as you don't assign a variable name to the output of a specific operation, Matlab will store it in a temporary variable called ans.
You can list all the variables in the workspace by typing who, and whos will also give the size and contents.
You can see what m-files are in your current directory with the command what.
Your first challenge is to find a way to read the numbers in the first two columns of this spreadsheet into a Matlab matrix called data, and plot it out.
[Hint: You can export the values to an ASCII file (e.g., as comma separated variables, CSV) or pasting them into a text editor.
See the Matlab load function.]
x = data(:,1);
y = data(:,2);
Measure the area under the curve, using the sum function.
Using the polyfit function, fit a straight line to a section of the data, the y values from 50 up to 100.
For example, if you store the calculated linear regression in a variable called z, you can overlay it onto your plot as follows:
You can investigate other types of curve fitting through the menus in the figure window.
See if you can use [ Tools | Data fitting ] to match the 1st-order function that you just computed.
Use the randn function to generate a sample of 100 normally-distributed random data points in a vector, specifying the mean μ = 5 and standard deviation σ = 2.
Show the distribution of the sample by plotting a histogram in the top half of the figure window:
axis([0 10 0 25]);
Edit the commands above if you want to adjust the labels and axis ranges.
To fit a Gaussian curve to the data, you can calculate the mean and the standard deviation std or variance var.
Define a set of values finely spaced along the x-axis (e.g., f from 0 to 10 with 0.1 spacing), and evaluate the gaussian probability density:
which you can then plot in the lower half of the figure
Now, let's see if you can use the matrix inverse inv to solve this set of simultaneous equations:
a + 5b + 3c = 18
3a + 2b + 4c = 29
8a + 7b = 24
Generate a signal of a sinusoid in white noise:
f = 440;
fs = 16000;
N = 4096;
w = 0.25 * cos(([1:N]'*2*pi*f/fs) + (pi/3)) + 0.1*randn(N,1);
The waveform is a pure tone as if the note A was played mixed in with some white noise at a sampling rate of 16 kHz, and lasts about a quarter of a second.
If you like you could investigate using sound to play it out on the soundcard or wavwrite to write it to a WAV-format audio file.
In order to estimate the amount of pure tone at that frequency in the signal, you can calculate the real and imaginary parts according to the equation for the Discrete Fourier Transform.
Store the result as a complex number Wf.
[Hint: make sure you perform a pointwise multiplication (.*) of the sinusoidal basis function (cosine or sine) with your signal.]
For comparison, calculate the entire spectrum of the signal by Matlab's built in fast Fourier transform fft:
W = fft(w,N);
freq = [0:N-1]*fs/N;
and plot the magnitude spectrum on a decibel scale:
Finally, to show how your estimate that was made at the exact known frequency compares, add it to your graph:
Can you explain what you see?
Try experimenting with different signal lengths, levels of the tone and the noise, different frequencies and make sure you understand how changing these parameters alters the results.
Other tutorials that will introduce you to the more technical ways of working with Matlab can be found on the College of Engineering pages at the University of Michigan:
Root Locus |
Frequency Response |
State Space |
Thanks to the Carnegie Mellon University and the Control group at the College of Engineering, University of Michigan for use of their tutorial materials, partly funded by the National Science Foundation (USA).
A revised version of these tutorials is available as a CD-ROM from Prentice Hall (ISBN 0-201-47700-9).