Introduction To MATLAB
Introduction To MATLAB
Objectives: Learn some basic Matlab commands which help you get comfortable with
Matlab.
Tasks:
1. Read this tutorial.
2. Repeat the steps of all the examples in Matlab and reproduce the results.
3. Finish the practice problems (1), (2), (3) on pape 10, 13, 22, and write a report.
You can also run the “demo” command to get an idea of things which Matlab can do for
you.
Example data, which can be used to check loading data from and saving data to files.
Time T1 T2
0.00 306.00 125.00
1.00 305.00 121.00
2.00 312.00 123.00
3.00 309.00 122.00
4.00 308.00 124.00
5.00 299.00 129.00
6.00 311.00 122.00
7.00 303.00 122.00
8.00 306.00 123.00
9.00 303.00 127.00
10.00 306.00 124.00
11.00 304.00 123.00
1
Che446, Winter 2006 Matlab Tutorial
Command Function
quit quits matlab, returning you to the operating system.
exit same as quit.
who lists all of the variables in your matlab workspace.
whos list the variables and describes their matrix size.
clear deletes all matrices from active workspace.
clear x deletes the matrix x from active workspace.
... You can split a very long line in a program by using three dots.
save saves all the matrices defined in the workspace into the file,
matlab.mat
load loads contents of matlab.mat into current workspace.
save filename saves the contents of workspace into the file, filename.mat
save filename x y z saves the matrices x, y and z into the file titled, filename.mat
load filename loads the contents of filename into current workspace.
The file can be a binary (.mat) file or an ASCII (ordinary text file).
Default is filename.mat
If you want to load a text file use: load filename.txt
Command Function
plot(x,y) creates a plot of the vectors x & y. With x along the x-axis and y
along the y-axis.
plot(y) creates a plot of y. with numbers 1,2,3 etc. on the x-axis
subplot can be used to generate side-by-side multiple plots
grid applies a grid on the graphics plot.
title('text') places a title at top of graphics plot.
xlabel('text') writes 'text' beneath the x-axis of a plot.
ylabel('text') writes 'text' beside the y-axis of a plot.
text(x,y,'text') writes 'text' at the location (x,y).
text(x,y,'text','sc') writes 'text' at point x,y assuming lower left corner is (0,0) and
upper right corner is (1,1).
gtext('text') writes text according to placement of mouse
hold on maintains the current plot in the graphics window and draws
subsequent plots on the same figure.
hold off turns OFF the 'hold on' option.
bar(x) creates a bar graph of the vector x.
2
Che446, Winter 2006 Matlab Tutorial
bar(x,y) creates a bar-graph of the elements of the vector y, locating the bars
according to the vector elements of 'x'.
hist(x) creates a histogram.
3. Equation Fitting
Command Function
polyfit(x,y,n) returns the coefficients of the n-degree polynomial for the vectors x
and y.
n must be at least 1 larger than the length of the vectors x and y.
The coefficients are stored in order with that of the highest order
term first and the lowest order last.
polyval(c,x) calculates the values of the polynomial whose coefficients are
stored in c, calculating for every value of the vector x.
Command Function
max(x) returns the maximum value of the elements in a vector.
Note: This command will destroy any association that may exist
3
Che446, Winter 2006 Matlab Tutorial
5. Special matrices
Command Function
zeros(n) creates an nxn matrix whose elements are zero.
zeros(m,n) creates a m-row, n-column matrix of zeros.
ones(n) creates a n x n square matrix whose elements are 1's
ones(m,n) creates a mxn matrix whose elements are 1's.
ones(A) creates an m x n matrix of 1's, where mxn is the size of A
zeros(A) creates an m x n matrix of 0's, where mxn is the size of A
eye(n) creates the nxn identity matrix with 1's on the diagonal and zeros in
all other entries
6. Miscellaneous Commands
Command Function
length(x) returns the number elements in a vector.
size(x) returns the size m(rows) and n(columns) of matrix x.
rand returns a random number with uniform distribution between 0 and 1
randn returns a random number with a normal distribution with a mean of
0 and variance of 1.
7. Array Products
Sometimes it is desired to simply multiply or divide every element of an matrix by
the corresponding element of another matrix. These are called array operations in
Matlab. Array or element-by-element operations are executed when the operator is
preceded by a '.' (period).
a .* b multiplies each element of a by the respective element of b.
a ./ b divides each element of a by the respective element of b.
a .\ b divides each element of b by the respective element of a.
a .^ b raise each element of a to the power of b.
8. Transpose Of A Matrix
x' The transpose of a matrix is obtained by interchanging the rows and columns.
The Matlab operator that creates the transpose is the single quotation mark.
4
Che446, Winter 2006 Matlab Tutorial
Usage:
A = xlsread('filename') returns numeric data from first sheet in
Excel file filename.xls
5
Che446, Winter 2006 Matlab Tutorial
Notes:
a. Empty cells or cells with text create NaNs (Not a Number) in the numeric result.
b. Leading rows and columns of text do not create NaNs in the numeric result. This
makes it easier to load files that look like this:
Time Temp
12 98
13 99
14 97
c. To get available sheet names from file, call XLSFINO with two outputs.
For example:
[status, sheetNames] = xlsfinfo(filename)
d. When reading date fields from Excel files, the date numbers need conversion to a
MATLAB date. For example, if your Excel file contains:
4/12/99
4/13/99
4/14/99
Convert the data to MATLAB dates like this:
excelDates = xlsread(FILENAME)
matlabDates = datenum('30-Dec-1899') + excelDates
6
Che446, Winter 2006 Matlab Tutorial
Shortcut: When using the workstations, clicking on Up Arrow will recall previous
commands. If you make a mistake, the Delete key OR the Backspace key may be used to
correct the error.
Examples:
Note that the set of numerical values or elements of the matrix are bounded by square
brackets.
1. c is a scalar or a 1 x 1 matrix
>> c = 5.66
or
>> c = [5.66]
7
Che446, Winter 2006 Matlab Tutorial
An individual element of a matrix can be specified with the notation A(i,j) for the
element, for example: A(2,1)=2.
When Matlab displays a matrix on the monitor, it will be organized according to the size
specification of the matrix, with each row appearing on a unique row of the monitor
screen and with each column aligned vertically and right-justified.
A matrix can be defined by a number of Matlab expressions. Examples are listed below
for a 1 x 3 row vector, x, whose elements are x(1) = 2, x(2) = 4 and x(3) = -1.
>> x = [ 2 4 -1 ]
or
>> x = [ 2,4,-1 ]
Notice that brackets must be used to open and close the set of numbers, and notice that
commas or blanks may be used as delimiters between the fields defining the elements of
the matrix. Blanks used around the = sign and the brackets are superfluous; however, they
make the statement more readable.
A 2x4 matrix, y, whose elements are y(1,1)=0, y(1,2) = y(1,3) = 2, y(1,4) = 3, y(2,1) = 5,
y(2,2) = -3, y(2,3) = 6 and y(2,4) = 4 can be defined as
>> y = [ 0 2 2 3
5 -3 6 4 ]
or
>> y = [ 0 2 2 3 ; 5 -3 6 4 ]
The semicolon ";" is used to differentiate the matrix rows when they appear on a single
line for data entry.
The elements of a matrix can be defined with algebraic expressions placed at the
appropriate location of the element. Thus
A matrix can be defined by using previously defined matrices. Recalling the matrix, x,
defined earlier:
>> x1 = [ x 5 8 ]
creates the result
x1 = [ 2 4 -1 5 8 ]
8
Che446, Winter 2006 Matlab Tutorial
Notice that the value "0" is substituted for x(4) which had not been explicitly defined.
Note that every time a matrix is defined and an 'enter' keystroke is executed, Matlab
echoes back the result. To cancel this echo, the Matlab command line can include a
semicolon at the end of the line before the keystroke 'enter'.
Hence use,
>> z = [ y ; c ] ;
to avoid Matlab from displaying the result of the command.
Occasionally, a line is so long that it can not be expressed in the 80 spaces available on a
line, in which case a line continuation is needed. In Matlab, a line continuation is defined
using three successive periods, "...". Thus
>> 4 + 5 + 3 ...
+ 1 + 10 + 2 ...
+5
gives the result
ans = 30
Notice that in this simple arithmetic operation, no matrix was defined. When such an
operation is executed in Matlab, the result is assigned to the matrix titled "ans". A
subsequent operation without an assignment to a specific matrix name will replace the
results in 'ans' by the result of the next operation. In the above, 'ans' is a 1x1 matrix, but it
need not be so in general.
If this is your first lesson using Matlab, execute the Matlab commands 'who' and whos'
before you 'quit'. Note that each of these commands lists the matrices you have defined in
this session on the computer. The command 'whos' also tells you the properties of each
matrix, including the number of elements, the row and column size (row x column) and
whether the elements are complex or real.
9
Che446, Winter 2006 Matlab Tutorial
IMPORTANT! If you execute the Matlab command 'save' before you quit, all of the
matrices that have been defined will be saved in a file titled matlab.mat stored in your
workspace. Should you desire to save specific matrices during any session, the command
'save' followed by the name of the matrix can be executed. More detail on how to save
and recall your matrices is discussed in Lesson 2.
Determine the size and result for the following matrices. Subsequently, carry out the
operations on matlab that define the matrices, and check your results using the 'whos'
statement.
1. a = [1,0,0,0,0,1]
2. b = [2;4;6;10]
3. c = [5 3 5; 6 2 -3]
4. d= [3 4
5 7
9 10 ]
5. e = [3 5 10 0; 0 0 ...
0 3; 3 9 9 8 ]
6. t = [4 24 9]
q = [t 0 t]
7. x = [ 3 6 ]
y = [d;x]
z = [x;d]
8. r = [ c; x,5]
9. v = [ c(2,1); b ]
10. a(2,1) = -3 (NOTE: Recall matrix "a" was defined in question (1) above.)
10
Che446, Winter 2006 Matlab Tutorial
! ASCII Files
An ASCII file is a data file containing characters in ASCII format, a format that can be
read using a text editor like notepad. It is independent of Matlab or any other executable
program. Using a text editor you can simply prepare a data file for which each row of
the matrix is a unique line in the data file, with the elements in the row separated by
blanks.
1. Example: 3 x 3 matrix saved in text file named x.dat
2 3 6
3 -1 0
7 0 -2
If these elements are formatted as described above and stored in a filename titled,
for example, x.dat, the 3 x 3 matrix x can be loaded into Matlab by the command:
>> load x.dat
! Binary files built using Matlab
1. If at any time during a matlab session you wish to store all matrices that have
been defined in the workspace, the command
>> save filename
will create a file in your directory that is titled filename.mat. The file will be in
binary format, understandable only by Matlab. Note that Matlab appends the
.mat suffix automatically.
2. Any number of matrices can be stored under the filename. Thus the command
string
>> save stuff x y z
will store the matrices x, y and z in the file titled stuff.mat.
3. If, you type the command save as in:
>> save
all of the current matrices defined in your workspace will be stored in the file
matlab.mat.
The load command for Matlab (Binary files) follows the same format as that defined for
ASCII files. However, you can omit the file suffix .mat when loading such files.
11
Che446, Winter 2006 Matlab Tutorial
! Colon Operator
1. The colon operator ':' is used to perform special and useful operations. If two
integers are separated by a colon, Matlab will generate all of the integers between
these two integers.
>> a = 1:8
generates the row vector, a = [ 1 2 3 4 5 6 7 8 ].
2. If three numbers, integer or non-integer, are separated by two colons, the middle
number is interpreted to be a "range" and the first and third are interpreted to be
"limits". Thus
>> b = [0.0 : 0.2 : 1.0]
generates the row vector, b = [ 0.0 0.2 0.4 0.6 0.8 1.0].
3. The colon operator can be used to obtain vectors from matrices. Thus if
>> x = [ 2 6 8
0 1 7
-2 5 -6 ]
The command
>> y = x(:,1)
(read as y = all rows in the first column of x)
creates the column vector
y = [2
0
-2]
4. The command
>> yy = x(:,2)
creates
yy = [ 6
1
5]
5. The command
>> z = x(1,:)
creates the row vector z = [ 2 6 8 ]
6. The colon operator is useful in extracting smaller matrices from larger matrices. If
the 4 x 3 matrix c is defined by:
>>c = [ -1 0 0
1 1 0
1 -1 0
0 0 2]
Then >> d1 = c(:,2:3) creates a matrix for which all elements of the rows from the 2nd
and third columns are used.
12
Che446, Winter 2006 Matlab Tutorial
1. The clc simply clears the screen, but does not clear or erase any matrices that have
been defined.
2. The command clear erases or removes matrices from your workspace. Use this
command with care.
3. The command
>> clear x y z
clears the matrices x, y and z from the workspace.
4. The command
>> clear
clears all the existing variables from the workspace.
Determine the content and size of the following matrices and check your results for
content and size using Matlab.
1. a = g(:,2)
2. b = g(4,:)
3. c = [10:15]
4. d = [4:9;1:6]
5. e = [-5,5]
6. f= [1.0:-.2:0.0]
7. t1 = g(4:5,1:3)
8. t2 = g(1:2:5,:)
13
Che446, Winter 2006 Matlab Tutorial
A Cartesian plot is based on plotting the x,y data pairs from the specified vectors.
Clearly, the vectors x and y must have the same number of elements. Imagine that you
wish to plot the function exp(x) for values of x from 0 to 2.
Notice that the command plot(x,y) opens a graphics window. If you now execute the
command 'grid', the graphics window is redrawn. (Note you move the cursor to the
14
Che446, Winter 2006 Matlab Tutorial
command window before typing new commands.) To avoid redrawing the window, you
may use the line continuation symbol.
Consider
>> plot(x,y),...
grid,...
title('Exponential Function'),...
xlabel('x'),...
ylabel('exp(x)'),
text(0.6,0.4,' y = exp(x)','sc')
Note that if you make a mistake in typing a series of lines of code, such as the above, the
use of line continuation can be frustrating. In a future lesson, we will learn how to create
batch files (called '.m' files) for executing a series of 'matlab' commands. This approach
gives you better opportunity to return to the command string and edit errors that have
been created.
Try the commands plot(x) and plot(y) to ensure you understand how they differ from
plot(x,y).
Notice that 'matlab' draws a straight line between the data-pairs. If you desire to see a
relatively smooth curve drawn for a rapidly changing function, you must include a
number of data points. For example, consider the trigonometric function, sin(x1)
(x1 is selected as the argument here to distinguish it from the vector 'x' that was defined
earlier.)
Plot sin(x1) over the limits 0<x1<pi. First define x1 with 5 elements,
>> x1 = 0 : pi/4 : pi
>> y1 = sin(x1)
15
Che446, Winter 2006 Matlab Tutorial
>> plot(x1,y1)
This hardly looks like the portion of the familiar sine wave. This is because the number
of points plotted is small and these have been joined by straight lines. To get a smoother
wave, we need more data points. Now, repeat this after defining a new vector for x1 and
y1 with 21 elements. (Note the use of the semicolon here to prevent the printing and
scrolling on the monitor screen of a vector or matrix with a large number of elements!)
>> x1 = 0 : 0.05*pi : pi ;
>> y1 =sin(x1);
>> plot(x1,y1)
16
Che446, Winter 2006 Matlab Tutorial
Bar Graphs
To observe how Matlab creates a bar graph, return to the vectors x,y that were defined
earlier. Create bar graphs using these or other vectors you may define. Of course the 'title'
and 'text' commands can be used with these graphs as well.
>> x1 = 0 : 0.05*pi : pi ;
>> y1 =sin(x1);
>> bar(x1,y1)
1
0.8
0.6
0.4
0.2
0
-0.5 0 0.5 1 1.5 2 2.5 3 3.5
Multiple Plots
More than a single graph can be presented on one graphic plot. One common way to
accomplish this is hold the graphics window open with the 'hold' command and execute a
subsequent plotting command.
Note: The hold command will remain active until you turn it off with the command hold
off.
17
Che446, Winter 2006 Matlab Tutorial
You can create multiple graphs by using multiple arguments. In addition to the vectors
x,y created earlier, create the vectors a,b and plot both vector sets simultaneously as
follows.
Note: Multiple plots can be accomplished also by using matrices rather than simple
vectors in the argument. If the arguments of the plot command are matrices, the columns
of y are plotted on the ordinate against the columns of x on the abscissa.
Lines can be colored and they can be broken to make distinctions among more than one
line.
18
Che446, Winter 2006 Matlab Tutorial
4 4
3 3
2 2
1 1
0 0
0 20 40 60 0 20 40 60
t t
1 1
0.5 0.5
0 0
-0.5 -0.5
-1 -1
0 20 40 60 0 20 40 60
t t
19
Che446, Winter 2006 Matlab Tutorial
To accomplish this using an m-file, we will call the file explot.m. Open the file in the
Matlab editor and type the code below.
Note: Any text or commands typed on a line after the % symbol will be treated as a
comment and ignored during execution.
Store this file under the name explot.m in your Matlab directory. Now when you are in
Matlab, any time you type the command explot the x-y plot of the damped exponential
sine function will appear.
20
Che446, Winter 2006 Matlab Tutorial
Functions in Matlab
While m-file is just a combination of several commands which can be executed by typing
the name of the m-file on the command prompt, the m-file cannot be called (or used) by
any other m-file. If there is any particular operation which you are going to use again-
and-again (with possibly different numbers), then you can write that operation as a
function. An example of a function to calculate mean of a vector is given below.
% An example of a function to calculate mean of a vector. Note that matlab already has a
% function of its own: called “mean” to calculate mean of a vector. So, this is just for
%illustration
function xbar=mymean(x)
a=length(x);
sum_x=0;
for i=1:a
sum_x=sum_x+x(i);
end
xbar=sum_x/a;
return
% function ends
The above function should be stored in a file named “mymean.m”. This function now can
be called in any m-file to calculate mean of a vector. The syntax for calling this function
would be:
21
Che446, Winter 2006 Matlab Tutorial
1. Plot the following three curves on a single plot and also on multiple plots (using
the subplot command): 2cos(t), sin(t), and cos(t)+sin(t). Use a time period such
that two or three peaks occur for each curve. Use solid, dashed, and + symbols for
the different curves. Use roughly 25-50 points for each curve.
2. a. Calculate the rank, determinant, and matrix inverse of the following matrices
(use help rank, help det, and help inv):
&1 2 1#
$
A = $− 1 − 2 − 1!!
$% 2 4 2 !"
&1 2 1#
B = $$− 1 4 − 1!!
$% 2 4 2 !"
&1 2 1#
C = $$− 1 4 − 1!!
$% 2 4 5 !"
3. Find C.C-1 where C is as defined in question 2.
4. Calculate xTx, and calculate xxT, where
&1 #
$2!
x=$ !
$ 3!
$ !
%4"
5. Find the eigenvalues of the matrix
&− 1 0 0 2 #
$ 1 −2 0 6 !!
D=$
$1 3 −1 8 !
$ !
%0 0 0 − 2"
6. Find the solutions to the equation f ( x) = 3x 3 + x 2 + 5 x − 6 = 0 . Use “roots” and
“fzero” commands.
22