Matlab Tutorial PDF
Matlab Tutorial PDF
Matlab Tutorial PDF
1 What is Matlab?
Matlab is a computer language with many ready-to-use powerful and reliable algorithms for doing
numerical computations. You can use it in an interactive manner like an advanced calculator,
or you can build up your own set of functions and programs. Excellent graphics facilities are
also available for visualizing your results.
2 Accessing Matlab
As of the Spring 2018 semester, the following SMU computer labs have Matlab installed:
Some of the above computer labs (Clements G15, Junkins 102, etc.) are only accessible for
classroom use, and are not generally available. Those marked as “General SMU login” require
your standard SMU ID and SMU email password. Those labs marked as “Engineering login”
require an engineering account (all engineering students have an engineering account).
Southern Methodist University has a Total Academic Headcount (TAH) license for MAT-
LAB, Simulink, and add-on products. Faculty, researchers, and students may use these products
for teaching, research, and learning. The license allows individuals to install the products on
university-owned equipment, as well as personally owned computers. Here is the link:
https://www.smu.edu/OIT/Services/Info/Matlab
The student version costs $49, and is available for Windows, Mac, and Linux computers. If
you do this, you will not need to purchase any of the additional Matlab toolboxes for this course
(all available for an additional fee), so be careful not to check any extra boxes. Since many of
you will be using Matlab for future Math and Engineering courses as well, it may be a good
idea to purchase it now instead of later.
3 Matlab Tutorials
You can take online Matlab tutorials at
http://www.mathworks.com/academia/student_center/tutorials/
These interactive tutorials are deigned for students and are free. Please register to start learning
Matlab on your own pace.
There are also many books with instructions on using and programming in Matlab. It may
be useful to buy one to keep it as a reference.
4 Starting Matlab
On Windows systems, Matlab is started by double-clicking the Matlab icon on the desktop or
by selecting Matlab from the start menu. On OS X systems, Matlab is installed in the main
Applications folder, and can be opened by double-clicking the Matlab icon there. On Linux or
UNIX systems, Matlab may be started from any directory by typing matlab & in the terminal.
On all systems, starting up Matlab will take you to the Command window where the Com-
mand line is indicated with the prompt >>. You can use Matlab like a calculator by entering
and executing Matlab commands in this window. Later, you will learn how to write a Matlab
program and run your program like a command.
>> 1+4/2*5
>> 1+4/(2*5)
>> 1+(4/2)*5
>> 9^2
>> sqrt(81)
>> exp(0)
>> pi
>> sin(pi/2)
>> cos(pi/2)
>> tan(pi/4)
>> cot(pi/4)
Note that in the above commands, pi is used by Matlab for π, and Matlab’s trigonometric
functions are permanently set to radians mode.
Here is a useful tip. You can bring up a previous comand by hitting the up-arrow key ↑
repeatedly until the command you want appears at the >> prompt. You can then use keys ←,
→, and ’Delete’ to edit the command. If you don’t want to cycle through every command you’ve
used, you can start typing the same command and then use the up-arrow to cycle through only
your previous commands that started with the same letters.
6 Order of operations
Matlab follows the standard mathematical order of operations in performing calculations. In
order of precedence, these are:
• operations in parentheses, ()
• exponentiation, ^
• multiplication and division, * and /
• addition and subtraction, + and -
For example, try the following operations
>> 4 - 2 * 3^2
ans =
-14
>> (4 - 2) * 3^2
ans =
18
>> 4 - (2 * 3)^2
ans =
-32
>> (4 - 2 * 3)^2
ans =
4
7 Variables
Not all calculations can or should be performed on a single line; instead it may be helpful to
store the results of calculations:
>> 1+4/2*5
ans =
11
>> ans*5
ans =
55
As you can see from the above results, if no name is given to a result, Matlab uses the variable
ans to store the result.
You can use a custom name for a variable. For example
>> a = 1+4/2*5
a =
11
>> A = a*5
A =
55
>> a
a =
11
As shown above, Matlab is case-sensitive, in that the variable a is different from the variable A.
Also as seen above, you can use a stored result in subsequent calculations.
These are examples of assignment statements: values are assigned to variables. Each variable
must be assigned a value before it can by used on the right of another assignment statement.
Please use meaningful names for your variables, such as weight, postion, balance etc., and
avoid using names that correspond with Matlab’s built-in functions and variables, such as pi
and cos. Finally, Matlab variable names must not include spaces; if you wish to separate
portions of a variable name you may use an underscore ( ), as in x velocity.
You can use the Matlab command whos to show you the active variables and their sizes
currently used in Matlab.
>> whos
Name Size Bytes Class Attributes
A 1x1 8 double
a 1x1 8 double
ans 1x1 8 double
8 Suppressing Output
You may not want to see the results of intermediate calculations, especially if those calculations
occur repeatedly within loops (more on loops later). If this is the case, you can suppress the
output of an assignment statement or an expression by adding a semi-colon ; at the end of the
statement or expression. For example,
With ; the value of x is hidden. Without ;, the values of y and z are displayed. Note also that
you can place several statements on one line separated by commas or semi-colons.
9 Keeping a Record
Issuing the diary command,
>> c = [1; 3
sqrt(49); 5]
c =
1
3
7
5
The entries of the column vector must be separated by semi-colons or by pressing Enter between
rows of the vector.
Try the following Matlab commands.
Note that the Matlab command length(r) gives the number of entries in the vector r. To
compute the mathematical length/magnitude of the vector, you can use the command norm(r),
which computes krk as the standard square root of the sum of the squares of each vector entry.
The length and norm functions work in the same manner for row and column vectors.
Here is an example of how to input a 3 × 2 matrix A.
>> A = [1 5; 7 9
-3 -7]
A =
1 5
7 9
-3 -7
As with row vectors, entries in each row are separated by spaces or commas. As with column
vectors, different rows are separated by semi-colons or by pressing Enter.
Try the commands
>> A = [5 7 9; 1 -3 -7]
A =
5 7 9
1 -3 -7
>> size(A)
ans =
2 3
The command size(A) gives a row vector, the first entry shows the number of rows and the
second the number of columns in the matrix A.
12 Special Matrices
Some matrices are used frequently in scientific computing, so Matlab provides functions to
construct such matrices directly. To create a n × n identity matrix:
>> I = eye(3);
I =
1 0 0
0 1 0
0 0 1
To create a m × n matrix of zeros:
>> A = zeros(2,3);
A =
0 0 0
0 0 0
To create a m × n matrix of ones:
>> A = ones(3,2);
A =
1 1
1 1
1 1
To create a m × n matrix full of uniformly-distributed random numbers between 0 and 1:
>> A = rand(1,5);
A =
0.8147 0.9058 0.1270 0.9134 0.6324
Finally, to create a m × n matrix full of normally-distributed random numbers with mean 0 and
standard deviation 1:
>> A = randn(3,1);
A =
-1.3077
-0.4336
0.3426
Note that the increment need not be an integer, nor must it be positive.
Another quick way to generate a row vector with evenly-spaced entries is to use the command
linspace. For example
>> linspace(1.1,1.5,5)
ans =
1.1000 1.2000 1.3000 1.4000 1.5000
>>
In general, linspace(s,e,n) generated a row vector with n evenly-spaced entries that start
with s and end with e (the increment is computed automatically from these inputs).
>> a = 2:5
a =
2 3 4 5
>> a(3)
ans = 4
The entry at row i and column j of a matrix A can be accessed as A(i,j). For example
Not only can you retrieve a specific value of a matrix or vector, but this same notation may
be used to change vector or matrix values. For example, following the previous commands, we
may do
>> A(2,3) = 5
A =
5 7 9
1 -3 5
6 8 10
You can access a range of entries of a vector or matrix by using index vectors generated by
colon notation. For example
>> A = [5 7 9; 1 -3 -7; 6 8 10]
A =
5 7 9
1 -3 -7
6 8 10
>> A(2:3,1:2:3)
ans =
1 -7
6 10
In this example, the accessed rows are specified by the vector 2:3, which are row 2 and 3, and
the accessed columns are specified by the vector 1:2:3, which are columns 1 and 3.
To access a whole row or column, refer to the following example
>> A = [5 7 9; 1 -3 -7; 6 8 10]
A =
5 7 9
1 -3 -7
6 8 10
>> A(2,:)
ans =
1 -3 -7
>> A(:,3)
ans =
9
-7
10
Note that A(2,:) retrieves the second row of the matrix A, and A(:,3) returns the thrid column
of the matrix A.
We note that the use of colon notation to access subsets of a vector or matrix is called array
slicing, and is a unique benefit of Matlab over most other programming languages.
15 Matrix Arithmetic
As long as the dimensions of a matrix arithmetic operation are allowable, Matlab can perform
matrix operations using natural mathematical notation.
15.4 Transpose
The transpose of a matrix A, denoted as AT in linear algebra, is obtained in Matlab by A’. For
example
>> A = [5 7 9; 1 -3 -7]
A =
5 7 9
1 -3 -7
>> A’
ans =
5 1
7 -3
9 -7
>> (A’)’
ans =
5 7 9
1 -3 -7
You can combine the transpose with matrix multiplication in interesting ways. For example,
you can compute the inner product of the column vectors a and b using the command a0 ∗ b (or
equivalently b0 ∗ a). Similarly, you can compute the outer products of these column vectors as
a ∗ b0 and b ∗ a0 . For example
>> a=[1;2;3]
a =
1
2
3
>> b=[4;5;6]
b =
4
5
6
>> a’*b
ans =
32
>> b’*a
ans =
32
>> a*b’
ans =
4 5 6
8 10 12
12 15 18
>> b*a’
ans =
4 8 12
5 10 15
6 12 18
>>
>> A = [5 7 9; 1 -3 -7]
A =
5 7 9
1 -3 -7
>> A+100
ans =
105 107 109
101 97 93
If you want to apply entry-wise operations such multiplication, division or power on matrices,
you can supply a . preceding the arithmetic operator. For example
>> A = [5 7 9; 1 -3 -7]
A =
5 7 9
1 -3 -7
>> B = [1 7 3;-1 3 7]
B =
1 7 3
-1 3 7
>> A.*B
ans =
5 49 27
-1 -9 -49
>> A./B
ans =
5 1 3
-1 -1 -1
>> A.^2
ans =
25 49 81
1 9 49
Note that A.*B produces a matrix (with the same size as A and B) with each entry being the
product of the corresponding entries in A and B.
Here is another example of a “dot” operation.
This example shows how to generate a vector with each entry being the reciprocal of the corre-
sponding entry of another vector.
16 Outputing/Plotting Results
16.1 disp
The Matlab function disp(x) displays the array x, without printing the array name. If x is a
string, the text is displayed. For example
>> r = [1 0.5 0.25 2];
>> disp(r)
1.0000 0.5000 0.2500 2.0000
>> disp(’Hello!’)
Hello!
>> s = ’Hello again!’;
>> disp(s)
Hello again!
16.2 fprintf
The Matlab function fprintf writes data in a controlled format on the screen (or into a file).
If you have ever used the printf command in C or C++, the syntax in Matlab is identical. For
example
In this example, the value of the variable balance is shown in the format controlled by %d
(meaning decimal number) at the location of the format control %d. The special format \n
means linefeed (another subsequent output will be on a new line). The other texts (except %d
and \n) are shown as they are within the quotation marks.
Please type help fprintf or doc fprintf to learn more on how to use fprintf.
16.3 plot
The Matlab function plot produces x-y plots. For example
>> a = [1 2 3];
>> b = [1 4 9];
>> plot(a,b)
The plot in Figure 1 is generated. What the Matlab function plot does in the example is to
draw a line that connects the three points (1,1), (2,4) and (3,9) on an x-y coordinate system.
The x-coordinates of the points are given by the vector a, and the y-coordinates of the points
are given by the vector b.
You can change in what shape the points are drawn, how they are connected, and what color
is used (by default, the points are drawn as dots and are connected by solid lines in blue). For
example
>> a = [1 2 3];
>> b = [1 4 9];
>> plot(a,b,’r--o’)
>> xlabel(’a’)
>> ylabel(’b’)
>> title(’b = a^2’)
1
1 1.2 1.4 1.6 1.8 2 2.2 2.4 2.6 2.8 3
Figure 1: An x-y plot of three points (1,1), (2,4) and (3,9) with Matlab’s default color, symbol
and line style.
When plotting data, it is always appreciated if you add labels to the x and y axes, and add a
title to the plot, as shown in this example. See the effect in Figure 2.
The final example below demonstrates one way to draw multiple curves in a single plot. Pay
attention to legend, which is used to name and distinguish each curve from one another.
>> t = linspace(-pi,pi,200);
>> s = sin(t);
>> c = cos(t);
>> plot(t,s,’b-’,t,c,’r--’)
>> xlabel(’t’)
>> legend(’sin(t)’,’cos(t)’)
17 for Loops
The primary way to do a repeated task in any programming language is through a loop. The
idea with a loop is that it will do a task repeatedly at every iteration of the loop.
The main loop structure in Matlab is the for loop. Below is a simple example:
5
b
1
1 1.2 1.4 1.6 1.8 2 2.2 2.4 2.6 2.8 3
a
Figure 2: An x-y plot of three points (1,1), (2,4) and (3,9) with changed color, symbol and line
style, and added labels and title.
1
sin(t)
0.8 cos(t)
0.6
0.4
0.2
−0.2
−0.4
−0.6
−0.8
−1
−4 −3 −2 −1 0 1 2 3 4
t
Note that the first line of the loop begins with the keyword for. The contents (i.e. the command
fprintf in this example) of the loop follow this first line, and cease just before the keyword end.
The syntax for i=1:2:5 indicates that the variable i takes in turn each value in the vector
1:2:5, and the contents of the loop are repeatedly executed for each value of i.
Below is another example:
50
40
30
20
>>
Now let’s use a loop to compute the sum 100 + 99 + 98 + · · · + 2 + 1. The trick here is to
define a variable, say s, and then add in turn each entry in the array 100 : −1 : 1 to s. The code
is
>> s = 0;
>> for i=100:-1:1
s = s+i;
end
>> disp(s)
5050
>>
Note that s is initialized to be zero (s = 0), and then it is updated with the command s = s+i
by adding the current value of i (taking one by one from the array 100:-1:1) to the current
value of s. You should understand this trick and know how to use it.
Suppose you need to generate an m × n matrix H with the entry hij = 1/(i + j − 1). You
can do using nested for loops as follows:
>> m=3;
>> n=4;
>> H=zeros(m,n);
>> for i=1:m
for j=1:n
H(i,j)=1/(i+j-1);
end
end
>> H
H =
if logical test 1
Commands to be executed if test 1 is true
elseif logical test 2
Commands to be executed if test 2 is true but test 1 is false
.
.
.
end
For complicated logical statements, it is standard to enclose the logic test in parentheses.
19 while Loops
Sometimes you want to repeatedly execute a section of codes until a condition is satisfied, but
you do not know in advance how many times you will need to repeat the codes. Since a for
loop needs to know how many times it will be evaluated beforehand, Matlab supplies another
(more advanced) looping mechanism, a while loop. For example,
>> i=0;
n=11;
while n<100
n=3*n;
i=i+1;
fprintf(’at step i = %d: n = %d\n’,i,n)
end
at step i = 1: n = 33
at step i = 2: n = 99
at step i = 3: n = 297
Note that the commands of the while loop are executed 3 times, as shown by the counter i,
and when the loop finishes, n = 297 and the condition n<100 is no longer satisfied.
20 Making M-Scripts/M-Files
You can store your Matlab commands (such as assignment statements, loops, and other state-
ments) into files called m-scripts. You can then run your files again and again at any time you
want to. Basically, your files act as lists of Matlab commands, where the Matlab commands
you type into your m-script are executed in the order from top to bottom. An m-file is very
useful because it allows you to pack many commands with logical order into one file to fulfill
a complicated computational task. This is Matlab programming. You will learn more about
programming later.
To create a new m-script file, click the icon ’New M-File’ on the tool bar or select the menu
’File→New→M-File’ from the menu list. To edit an old m-script file, click the icon ’Open file’
on the tool bar or select the menu ’File→Open’. These operations will open the Matlab Editor
for you to input or edit comands. Note that a m-script file must be saved with a “.m” extention.
For example, test.m. You can run your file (i.e. the commands contained in the file) by typing
test at the prompt >> in the Command window.
Alternatively, a Matlab m-file is just a plain text file with a “.m” extension, so if you prefer
you can use a different text editor than the built-in Matlab one.
An m-script can be published to a webpage as a .html file by selecting in the Matlab Editor
the menu ’File→Save and Publish to-HTML’. The webpage includes the commands in the m-
script followed by the displayed results of these commands.
Lastly, any line in a m-file starting with % is just a comment that is not executed by Matlab.
These should be used to help others and yourself understand your code. Similarly, a line starting
with %% will show up as a link at the beginning of the published webpage.
21 Function M-Files
You have seen some built-in Matlab functions such as sin, cos and so on. If you want to use
sin to compute sin(π), you can do the following
>> y=sin(pi)
y =
1.2246e-16
In the above example, the function has the name sin, it receives the value pi as an input in the
parentheses following its name, and it returns the result to the variable y.
Also note that in this example the value of sin π given by Matlab is very close to zero, but
not exactly zero. This is due to floating-point roundoff error, which you will learn more about
in Math 3315.
Matlab enables you to create your own functions called function m-files in a similar way as
the above example. For example, the following function m-file is created to find the two roots
of the quadratic equation ax2 + bx + c = 0, under the assumptions that a 6= 0 and that the
equation has real-valued roots:
function [x1 x2] = quadroots(a,b,c)
sdelta = sqrt(b^2-4*a*c);
x1 = (-b+sdelta)/(2*a);
x2 = (-b-sdelta)/(2*a);
As you can see, unlike a Matlab script, the function m-file starts with the keyword function.
Here, the created function is named quadroots – you should use other meaningful names as
you like. The function receives the coefficients a, b and c, and it returns the two roots x1 and
x2, which are listed between the square brackets at the left-hand side of the equal sign. The
main body (the codes after the first line) of the function m-file applies formulas to compute the
two roots using the received coefficients. This function m-file must be saved with the file name
quadroots.m, i.e. the root of the file name must be the same as the function name, such that
other m-scripts or function m-files know where (which file) to find the codes when they call/use
the created function by the name quadroots. Furthermore, as with Matlab variable names,
Matlab function names must not contain spaces.
After the function quadroots is created and saved, you can test it by using another m-script,
as long as both of the m-files are located in the same directory on the computer. Below is an
example of a test m-script, which can be saved as a file with any name, e.g. testquadroots.m
aa=1;
bb=0;
cc=-4;
[root1 root2] = quadroots(aa,bb,cc);
fprintf(’the roots are: %d and %d\n’,root1,root2)
Note that when using quadroots, the input variables (aa,bb and cc) passed to it can have
different names as those in the input list (a, b and c) of the function m-file above, but they must
have been assigned values and must be in the correct order (i.e. aa corresponds to a and so on).
Likewise, the returned values of the roots are assigned to the variables root1 and root2 in the
order determined by the function m-file, but the names of the variables these are assigned to
can be different from the names in the function m-file.
A function m-file has the following general form:
function [output1, output2, ...] = name(input1, input2, ...)
...
output1 = ...;
...
output2 = ...;
...
22 Anonymous Functions
Many functions do not require much space, or you may want them to change as a program
proceeds. In such cases, creating an entire function m-file to hold the small function, or creating
many function m-files to hold each version of a function, may be unnecessary. In such situations,
Matlab allows you to declare an anonymous function. These may be defined in a script m-file,
a function m-file, or even in an interactive Matlab session. For example, to create a simple
function that implements g(x) = cos(πx) you can use the Matlab code
g = @(x) cos(pi*x);
This function will persist in the namespace of the function, script or session where it is defined,
similar to a Matlab variable. A few rules about anonymous functions:
• The function name is listed at the left of the equal sign to the left of the ampersand.
• All arguments to the function must be listed in the parentheses following the ampersand.
• The function can see and use any other variables defined previously within the file.
a = 2;
b = -3;
c = 1;
d = 8;
f = @(x,y) a*(x-b)^2 + c*(y-d)^2;
clear a b c d
x = linspace(-5,-1,100);
y = linspace(4,12,200);
z = zeros(100,200);
for i=1:100
for j=1:200
z(i,j) = f(x(i),y(j));
end
end
surf(y,x,z)
Because a, b, c and d were available at the time f was defined, the anonymous function handle
includes those values even though they were deleted prior to using f.
Concluding Remarks
Matlab is a powerful computing environment that has been built up over many years as a tool
for scientific computing. As a result, no tutorial can give an exhaustive account of all Matlab
functionality, though we believe that this tutorial should be enough to help you get started. As
with any technology tool, the best way to learn is through practice, through sharing tips with
others, and through reading the documentation. Good luck!