Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Matlab Tutorial
Matlab Tutorial
MATLAB also has other windows including the Figure Window to display graphs and the
Editing Window see in the figure below.
MATLAB Tutorial
Tutorial 1
INTRODUCTION
MATLAB is a an interpreted mathematical language and computational tool whose name is
short for Matrix Laboratory. Interpreted languages (i.e. MATLAB, LISP etc.) are usually much
easier to use, but are not as numerically efficient as compiled languages (i.e. FORTRAN, C,
Pascal etc.). Given the origin of MATLABs name its default mode for arithmetic operations is in
matrix notation. Special syntax is sometimes required to force MATLAB to interpret things
like a scalar like most computational tools. MATLAB allows for the simple calculation of
many mathematical problems and it also contains typical programming structures to allow the
writing of programs. MATLAB does numerical calculations, as well as symbolic calculations
similar to MAPLE and MATHEMATICA but through the use of a special toolbox.
MATLAB is a registered trademark of The MathWorks Inc.
As see in the figure below MATLAB version 7 has various window sections
BASIC OPERATIONS
Upon starting MATLAB you may see various messages regarding the loading of various
toolboxes. Once this is completed you will see the MATLAB prompt (which looks like a double
greater than sign >> ). You may type basic variable assignments and mathematical operations at
the prompt in a fashion similar to various calculator interfaces and other mathematical tools like
MAPLE of MATHEMATICA. Typing the RETURN key will carry out the calculation.
Workspace gives
information on
current variables
Command window
shows commands
and results
1.5000
>>
3^2
ans =
9
>>
2*pi
ans =
6.2832
>>
Command history
(3*4+7)/(6+11)/2 + 3^1.3
ans =
4.7300
The standard operators in MATLAB work for both matrices and scalars.
ZK Nagy
ZK Nagy
Matlab Tutorial
Matlab Tutorial
Exercise 3:
Basic Operations
Operation
symbol
addition
+
subtraction
multiplication
*
division
/
to the power of
^
>>
2*pi
ans =
6.2832
>> pi=1
pi =
1
Note that the calculation is always returned in the default variable ans which is the answer
to the last calculation done. Values can also be assigned to variable names with the equal
sign, and these variables may also be used in calculations as seen in the examples below
>> 2*pi
ans =
2
Exercise 2
>> DOUBLEPI = 6.2832
If you wish to put things back to their default assignments simply clear your variables with the
clear command which is explained below under MATLAB ADMINISTRATION. Some other
special variables and functions are given in the tables below.
DOUBLEPI =
6.2832
>>
var1=4
var1 =
Variable
ans
pi
computer
i or j
inf
eps
NaN
4
>> var2=9.2
var2 =
9.2000
>> var3=var2+var1
var3 =
Special Variables
variable value
most recent answer
13.2000
>> var1=DOUBLEPI/2
symbol
var1 =
3.1416
Please be careful of what variable names you choose because MATLAB will overwrite its own
variables and functions. Since MATLAB is case sensitive you can avoid this by using capital
letters for your functions and variables because most of MATLABs built in functions are in
lowercase (just the opposite of MATHEMATICA). For example you can overwrite pi as seen
below:
ZK Nagy
ZK Nagy
Matlab Tutorial
Matlab Tutorial
Note that the individual elements of a vector or matrix are assembled between square brackets
and may be separated by spaces or by commas as seen above. To assemble a matrix you may use
a semicolon to separate individual rows as seen below.
Exercise 5
>> A=[1 1 1; 1 2 3; 2 -2 1]
A =
1 1 1
1 2 3
Exercise 4
2 -2 1
>> a=[1 2 3]
a =
Matrices can also be assembled using colons which work like loops. The syntax is:
MATRIX=[start:increment:finish] where MATRIX above is a vector containing a
sequence of values starting from start and counting up the finish with a step size of
increment as seen in the example below. Note that if the increment value is omitted an
increment of 1 is assumed.
1 2 3
>> b=a'
b =
1
Exercise 6
>> a=[1:1:3]
a =
>> a*b
1
ans =
>> b=[1:3]
14
b =
The example above illustrates the assembly of a row and column vector which are then
multiplied together. This example introduces the transpose operator which is an apostrophe
(). The transpose operator simply interchanges the rows and columns of a matrix. It is easy to
type matrices into MATLAB as rows, and the transpose operator will help you align data as
columns. Please note that MATLAB adheres to the standard rules of matrix algebra and will
not let you violate them by multiplying a row vector by a row vector as see below.
>> a=[1 2 3]
a =
>> c=[10:-2:0]
c =
10
>> b=a
b =
1 2 3
>> a*b
??? Error using ==> *
Inner matrix dimensions must agree.
There are many special functions used to quickly assemble matrices some of these are listed in
the table below.
Function
eye
zeros
ones
rand
randn
diag
1 2 3
Special Matrices
creates an identity matrix
creates a matrix or vector of all zeros
creates a matrix or vector of all ones
creates a matrix or vector filled with uniformly distributed random numbers
creates a matrix or vector filled with normally distributed random numbers
create or extract matrix diagonal
The syntax of each of these functions is discussed under their headings in the help command
(discussed below under MATLAB ADMINISTRATION).
ZK Nagy
ZK Nagy
Matlab Tutorial
Matrices can also be assembled from other matrices using commas or semicolons as seen below.
Exercise 7
>> a=ones(1,3)
a =
1
1
1
>> b=[1:3]
b =
1
2
>> c=[2 -2 1]
c =
2
-2
>> A=[a, b, c]
A =
1
1
Matlab Tutorial
Matrix manipulations can be carried out using the colon operator (:). When accessing parts of a
matrix the matrix name is followed by closed parentheses where the first index is the row and the
next index separated by comma is the column. In addition to the lists as seen above the colon by
itself refers to all rows or columns in a matrix. For example taking matrix A below we can make
various manipulations.
Exercise 9
-2
1
5
9
2
6
10
3
7
11
4
8
12
13
14
15
16
>> A=[a; b; c]
A =
1
1
1
2
1
3
>> A(2,3)
-2
ans =
7
Almost any function in MATLAB can be used on a matrix. For example, sin(A) would be a 22
matrix that has the value of sine of each element of A. Some important matrix functions are listed
in the table below:
A(2,:)
Matrix Functions
matrix calculation
ans =
function
inv
det
cond
eig
rank
expm
matrix inverse
matrix determinant
matrix condition number
eigenvalue-eigenvector calculation
matrix rank
martix exponential
5 6 7 8
>>
A(:,3)
ans =
3
7
11
15
To learn more about matrix functions first type >> help and press Return. A list of basic
operators will scroll down the screen. For further information about matrix functions type >>
help matlab\elmat and >> help matlab\matfun or go to the html help and electronic book files.
A(1:3,3:4)
ans =
Important functions the give information about the variables are, size (size of a matrix, vector)
and length (length of a vector)
Exercise 8
3
7
11
>>
>> length(a)
ans =
A(1,4:-1:1)
4 3 2 1
>> size(A)
ZK Nagy
4
8
12
ZK Nagy
Matlab Tutorial
Matlab Tutorial
Exercise 10
Now lets illustrate some other matrix functions using a system of linear equations as an example.
Since our linear system is written as in the former of the two examples we can use the
backward slash.
x1 + x2 + x3 = 6
x + 2x +3x = 14
1
2
3
2x1 2x2 + x3 = 1
>> A
A =
1 1 1
1 2 3
2 -2 1
6
b = 14
1
>> b
x = A 1b
b =
6
14
1
>> x=A\b
x =
1
2
3
b =
6
14
1
Exercise 11
By default MATLAB does math in matrix notation, to change to element by element place a
period in front of the operator. For example a^2 will carryout a*a while a.^2 will square every
element of matrix a.
>> A=[1 1 1; 1 2 3; 2 -2 1]
A =
1
1
2
1
2
-2
3
1
>> x=inv(A)*b
x =
1.0000
2.0000
3.0000
ans =
6.0000
14.0000
1.0000
>>
a=[1 2 3];
>>
b=[2 5 8];
>>
a*b
>> A*x
>>
a*b'
ans =
36
>>
Note that in the above example simply by typing a variable its contents are displayed. It is not
necessary to take the inverse of a coefficient matrix to find its solution. A simple application of
Gauss-Jordan elimination on the augmented matrix is more efficient that taking the matrix
inverse. MATLAB uses the metaphor of dividing by the coefficient matrix (as one would do in
a scalar equation) to solve this. The following syntax is used to solve a linear system depending
on how it is written.
for Ax = b use the backward slash:
x = A\b
x = b/A
ZK Nagy
a.*b
ans =
2 10 24
>>
a.^2
ans =
1 4 9
ZK Nagy
If we want the element by element product, we must put a period before the
multiplication symbol:
10
Matlab Tutorial
Matlab Tutorial
MATLAB ADMINISTRATION
There are a number of commands that allow you to control the MATLAB environment. Some
of these are listed in the table below.
Individual Exercise 1
For matrices A and B defined below, type the following commands and observe the results:
>> A=[5 6 7;10 4 6;2 8 10] <return>
command
help
whos
who
clear
clc
what
lookfor
>> A Transpose of A
>> A^2
>> A*B
>> A^(-1)
>> A*A
>> A./5
>> A/A
>> B*A
>> A.^2
>> A/B
>> 5*A
>> A-B
Individual Exercise 2
3. Create the row vector C from A and B that is equal to C=[1 2 3 4 .... 18]. Hint: Start with
C=A(?,?) then let C=[C B(?,?)] then C=[C A(?,?)],. Follow this pattern until you obtain the
desired C. You fill in the correct values for "?".
4. What would be a really easy way to create the vector C without even using matrices A and
B.
Command
cd
delete
dir
The first and most important command of this type is the help command because it allows
access to information on all other commands. Typing help shows all the categories of help as
seen below. For more help on directory/topic, type "help topic". Alternatively, typing of help
followed by a specific topic or function gives the details.
>> help clear
Of the remaining functions in the table above the second most important one is the whos
command. It shows the details of the currently defined variables as seen in the workspace.
7. Using A and B from Part 2 and D=[A B] determine which ones of the following will work:
a) A*D
e) A*D
i) A/D
b) D*A
f) A*D*B
j) D/A
c) A*B
g) A*B*D
k) D(:,(1:3))*A
d) D*A
h) A/B
l) D((1:3),:)*A
Hints:
- A useful property of the command line editor is that by using the cursor (arrow) keys you
may backtrack through previous commands and then edit them before executing them again
by hitting the return key. This is useful for complex commands, when you make typing
errors or want to repeat (and change) a previous command. The up and down arrows will step
through all the commands given since the MATLAB sessions was started. You can also use
the command history window to search and execute previous commands.
Individual Exercise 3
-
If you looking for a special command and you remember the first letter(s) the search is made
easier by typing those characters before using the arrow keys.
Several commands may be given on the same line in MATLAB. The commands are
separated by commas or by semicolon (to avoid display)
11
ZK Nagy
12
Matlab Tutorial
Matlab Tutorial
COMPLEX NUMBERS
PLOTTING
MATLAB works with complex numbers! Use i or j in the definition of the numbers. Note try to
avoid using i or j as variable names.
Numerous plotting capabilities exist in MATLAB; some of the useful commands are given in the
table below
Exercise 12
Introduce the following commands to the Matlab prompt
2D
>> z1 = 1+3*i
z1 =
3D
1.0000 + 3.0000i
>> z1 + 2*i
Generic
1.0000 + 5.0000i
>> z1^2
ans =
-8.0000 + 6.0000i
>> z2=3*j
z2 =
Plot commands
Command
Function
plot
linear plot 2-D points or lines
loglog
log-log plot 2-D points or lines
semilogx, semilogy semi-log plot 2-D points or lines
bar
plot 2-D bar graph
hist
plot histogram
plot3
plot 3-D points or lines
mesh
Plot 3-D mesh grid
surf
Plot 3-D surface plot
title
add title to graph
axis
modify axis scaling or appearance
xlabel, ylabel
add x or y axis label
hold on/off
holds the current plot
text
add text annotation
divides figure window
subplot
open new figure window
figure
adds the grid lines
grid
graph legend
legend
The table above contains only a small number of the MATLAB plotting commands, typing
help graph2d, help graph3d, and help
graphics for more information on MATLAB
plotting. The following example illustrates a simple
xy graph.
0 + 3.0000i
>> z2^2
ans =
Exercise 13
-9
>>
>>
>>
>>
>>
>>
>>
>>
>> sqrt(-4)
ans =
0 + 2.0000i
t=[0:0.01:10];
p1=cos(t);
p2=sin(t);
p3=p1.*p2;
plot(t,p1,t,p2,t,p3)
title('Example Plot')
xlabel('t (seconds)')
legend('cos', 'sin', 'cos(t)*sin(t)')
>> z1*conj(z1)
The above example will produce the first plot displayed above in the current plot window. Please
note that on the screen this plot will show up with each line plotted in a different default color.
However, these plots cant be copied into a report easily unless you have access to a color printer.
In order the make this plot easier to copy into a black and white report simply include an
additional field in the plot command for each curve to be graphed. These fields in quotes are
explained under the help utility for the plot. Write >> help plot to see the options of this
command.
ans =
10
ZK Nagy
13
ZK Nagy
14
Matlab Tutorial
In the 2nd plot below we have also added a title and a y axis label as well as plotting all the lines
in black with various types of lines. We also illustrate how to ad points to existing plots and plot
grid lines.
Exercise 14
Matlab Tutorial
figure
t=[0:0.01:10];
p1=cos(t);
p2=sin(t);
p3=p1.*p2;
plot(t,p1,'k--',t,p2,'k-',t,p3,'k:')
xlabel('t (seconds)');
ylabel('f(t)');
title('Example Plot 2')
legend('cos', 'sin', 'cos(t)*sin(t)')
>>
>>
>>
>>
>>
>>
t2 = [0:0.2:10];
p4= cos(t2);
hold on
plot(t2,p4,'kx')
hold off
grid
Exercise 15
We want to represent the surface given by the equation z = xy(x2-y2)/(x2+y2) on the interval [-3 3]
for both x and y.
linspace(a,b,N) generates N linearly
distributed values between a and b
Enter the following commands
>> x = linspace(-3,3,300);
and
You can edit the properties of the figure from the object editor, by using the edit tool
double clicking on the particular part of the figure. Example to make one of the lines thicker you
may follow the procedure below:
>> y = x;
1. Select
edit tool
2. Double
click on line
3. Increase
line thickness
ZK Nagy
15
ZK Nagy
16