Introduction to MATLAB
The MATLAB software environment is a scientific computing software developed and patented by the
Mathworks company. Free software Matlab clones are Octave and Scilab, which use however a
slightly different syntax.
MATLAB graphical user interface
The Matlab graphical user interface consists of several specific environments
the command window is the place where commands are typed and executed
the workspace shows all the variables that are currently saved in the memory, their type and
their value
the current folder shows all the files in the directory we are working in
the command history shows the history of the operations carried out up to now
the editor window allows to write series of MATLAB commands to be executed as scripts or
functions.
Line commands
In its simplest mode, Matlab can be used typing line commands in the command window.
For example, typing in the command window
7+5
one gets the answer displayed. The result is automatically assigned as value to the intrinsic variable
ans. The same result can be assigned to a different variable as its value
a=7+5
One can add a semicolon ; at the end of the command line to carry out a computation without
visualizing the result:
a=7+5;
In this case, the value of the variable is assigned, but not displayed. Notice that MATLAB is case
sensitive, so that variables defined with upper and lower case characters are different variables
A=2
a
The value of a defined variable can be visualized typing its name. To know which variables are in
memory in this moment, we can use the command
who
With the command
whos
one obtains, in addition to the name of the variable, also its size, the memory allocation and the type
of the variable.
Variables can be deleted with the command
clear A
who
Typing simply
clear
or
clear all
cancels instead the values of all the variables in the memory. The command
clc
can be used instead to clean the command window from the previously executed commands.
However, clc does not modify the values of the existing variables.
In order to obtain information on a specific command like clear, one can type
help clear
In order to access the full MATLAB documentation one has to use instead the command
doc
Integers and real numbers are defined in Matlab. Some important real constants are predefined, for
example
pi
Another predefined constant is the imaginary unit, which is contained in the variables i and j
i
j
The default visualization of real number is with only 4 digits. In order to visualize real numbers in
different formats, one can use the command format. For example
format long
pi
allows to display all the 16 significant digits that MATLAB is using. The full set of available formats
can be found typing
help format
The main arithmetic operations are defined in MATLAB
Sum a+b
Difference a-b
Product a*b
Division of a by b a/b
a to the power b a^b
along with a number of standard mathematical functions
square root of x sqrt(x)
exponential of x exp(x)
natural logarithm of x log(x)
logarithm of x in base 10 log10(x)
logarithm of x in base 2 log2(x)
absolute value of x abs(x)
cosine of x cos(x)
arccosine of x acos(x)
sine of x sin(x)
arcsine of x asin(x)
tangent of x tan(x)
arctangent of x atan(x)
hyperbolic cosine of x cosh(x)
inverse hyperbolic cosine of x acosh(x)
hyperbolic sine of x sinh(x)
inverse hyperbolic sine of x asinh(x)
hyperbolic tangent of x tanh(x)
inverse of hyperbolic tangent of x atanh(x)
Exercise 1
Compute the following expressions with Matlab:
Exercise 2
Set x = 3 and y = -2 and evaluate the following expressions with MATLAB:
Vectors and matrices
MATLAB can work with arrays and matrices of integer or real numbers with an arbitrary number of
rows and columns. Actually, MATLAB is the acronym of MATrix LABoratory and all variables in
MATLAB are matrices. In particular, scalar variables are 1x1 matrices, vectors are matrices with only
one row (1xn) or only one column (nx1), denoted as row and column vectors, respectively, where n is
the vector length. The row vector is defined by the command
x = [1 2 3]
or
x = [1, 2, 3]
while the column vector is defined by the command
y = [4; 5; 6]
Transposition, denoted by a prime after the vector variable, transforms a row vector into the
corresponding column vector and viceversa:
z=y'
The command creates a vector which contains a first element is n and then elements
until the maximum value is lower or equal to p if or the minimum value
is larger or equal to p if . For example
d = [1:3:8]
or
f = [10:-2:2]
If the step p is omitted, it is assumed to be equal to 1:
g = [1:4]
The step can be also a real number
h = [0:0.5:2]
We can use also the command to define a vector of n equally spaced values
from a to b, as for example
p = linspace(0,5,6)
Also full matrices can be built, for example by defining them row by row
A = [1 2 3; 4 5 6; 7 8 9]
or column by column
B=[[1;2;3],[4;5;6],[7;8;9]]
Also rectangular matrices can be defined
C=[exp(1) pi sqrt(2); 0 0 0]
Once matrices have been defined, their values can be modified individually. For example, to set to
zero the element in the second row, third column of matrix one can write
A(2,3)=0;
A
Operations on vectors and matrices
All mathematical operators and functions can be applied to vectors componentwise.
Componentwise operations can be carried out only if the involved vectors (matrices) have the same
dimension, for example
a=[1 2 3];
b=[4 5 6];
c=a+b
but if the dimensions do not match we obtain an error message
d=[1 2 3];
e=[4 5 6 7];
f=d+e
All the functions introduced before can be applied to vectors (matrices) componentwise. For example,
we can compute the absolute value of all the components of a vector as follows
d=[-1 2 -3]
e=abs(d)
or the cosines of all the components of a vector as
f=cos(d)
Notice that some operators must be precedeed by a dot to obtain componentwise action on a vector
(or matrix) or pair of vectors (or matrices). In particular, this is true for the product operator and all
operators derived from it. Indeed, since all MATLAB objects are matrices, the default product operator
in MATLAB is the matrix row-by-column product, for which, given a matrix with m rows and k
columns and a matrix with k rows and n columns one defines
as the matrix with m rows and n columns whose elements are computed as
Therefore, the operands of a product operation must also have matching numbers of rows and
columns. One can compute
a=[1 2 3]
b=[4;5;6]
c=a*b
which yields the row by column product of these two vectors. Typing instead
a=[1 2 3]
b=[4 5 6]
c=a.*b
yields the componentwise product of these two vectors. Considering also more general matrices,
one can define for example
A = [1 2 3; 4 5 6; 7 8 9];
b = [1 2 3]';
and compute the row by column product
y=A*b
and also
z=b'*A
or define the matrix
B = [0 1 -1; 1 0 0; -2 0 3]
and compute the products
C = A * B
D = B * A
It can be seen that, as well known from linear algebra, the matrix row by column product is non
commutative. Furthermore, according to its definition, it can only be computed if the number of
columns of the first matrix is equal to the number of rows of the second matrix, so for example trying
to compute
a=[1 2 3]
b=[4 5 6]
c=a*b
results in an error. A summary of several vector operations in MATLAB is the following:
k*x product of a scalar k by a vector , multiplies all components of by k
x+y sum of two vectors , yields a vector whose components are the sums of the
corresponding components of
x-y difference of two vectors , yields a vector whose components are the differences of
the corresponding components of
x.*y componentwise product of two vectors of the same size, yields a vector whose
components are the products of the corresponding components of
x./y componentwise division of two vectors of the same size, yields a vector whose
components are the quotients of the corresponding components of
x.^k componentwise kth power of vector , multiplies all components of by themselves k
times.
In Matlab there are some important functions that are useful for the managing of vectors and
matrices.
Given the vector and the matrix we can compute the following quantities:
size(A) gives a vector with the number of rows and columns of the matrix
length(b) gives the number of elements of the vector
b(end) gives the last element of the vector
max(b) gives the maximum element in the vector
min(b) gives the minimum element in the vector
max(A) gives a row vector with the maximum elements in each column of the matrix
min(A) gives a row vector with the minimum elements in each column of the matrix
sum(b) gives the sum of all the elements in the vector
sum(A) gives a row vector with the sums of elements in each column of the matrix
diag(A) extracts the main diagonal of the matrix
diag(b) creates a diagonal square matrix with the elements of the vector on the main
diagonal
tril(A) creates a lower triangular matrix with the lower triangular components of the
matrix
triu(A) creates an upper triangular matrix with the upper triangular components of the
matrix
A(i,j) extracts the element on the i-th row,j-th column of the matrix
A(:,j) extracts the elements on the j-th column of the matrix
A(i,:) extracts the element on the i-th row of the matrix
zeros(m,n) builds a matrix with zero elements
zeros(n) builds a matrix with zero elements
ones(m,n) builds a matrix with elements equal to one
ones(n) builds a matrix with elements equal to one
eye(n) builds the identity matrix of dimension n
norm(b) computes the euclidean norm of the vector
Exercise 3
Define in MATLAB the following matrices and vectors:
Compute the matrices and vectors:
checking that
componentwise and with the row-by-column product; check that
One dimensional plots
Given two row (or column) vectors of the same size , the command
plot(x,y) opens a graphics window in which the points are drawn and
connected by line segments. The command plot has a great number of options to customize the
plot that can be visualized by help plot. For example, if we want to plot the graph of the function
on the interval sampling x with step we can proceed as follows
x = [-3:0.1:3];
y = x.^3 - 3*x.^2 + 2*x - 1;
plot(x,y)
Here is a summary of important graphical commands:
grid on overlays a reference grid on the plot
grid off removes the reference grid from the plot
semilogx produces plot using logarithmic scale on the x axis
semilogy produces plot using logarithmic scale on the y axis
loglog produces plot using logarithmic scale on the x and on the y axis
title('ZZZ') adds the title 'ZZZ' to the plot
xlabel('XXX') visualizes 'XXX' along the x axis
ylabel('YYY') visualizes 'YYY' along the y axis
legend inserts a legend in the plot
axis([xmin,xmax,ymin,ymax]) sets axes limits
figure opens a new graphic window
figure(n) opens a new graphic window numbered by n
hold on keeps the previous graph when next graph is plotted in the same
window
hold off stops keeping the previous graph when next graph is plotted in the
same window
clf clears content of active graphics windows
print prints content of active graphics window
Graphical windows opened by plot can be closed using the command close. For example, after
executing
x = [-3:0.1:3];
y = x.^3 - 3*x.^2 + 2*x - 1;
z=cos(x);
figure(1)
plot(x,y)
figure(2)
plot(x,z)
the command close(1) will close only window number 1.
Exercise 4
Plot the following functions in Matlab chosing an appropriate sampling of the interval on the x axis:
Scripts
Matlab can be used in interactive mode by typing commands directly in the command window, as
done in the previous sections. However, when long sequences of commands must be executed, it is
more convenient to do it by means of a script or m-file. This is a text file named with extension .m
that can be created by any text editor. Matlab has its own internal editor, which is more convenient to
use. A script must contain a sequence of valid Matlab commands. The Matlab text editor can be
opened from the command window, for example, with the command
edit script1.m
As an example, here is the content to be placed in a file for example vectors.m to define some
vectors and perform some actions on them:
% Comment header of file vectors.m
% Created on [Link] by [Link]
% Computes the sum of two vectors
x = [2 4 8];
y = [4 7 1];
z = x + y
Comments can be inserted in the script through the symbol % at the beginning of the line. An m-file
must be saved in the same directory in which it has to be executed, or in a directory whose path is
included in the list of paths automatically accessed by Matlab. After the script vectors.m has been
created, the commands in it can be executed by typing the script name in the command window:
vectors
Another example is the following content for a script plotting.m that allows to do some graphics:
% Comment header of file plotting.m
% Created on [Link] by [Link]
% Plots graph of x^3-3*x^2+2*x+1
x = [-3:0.1:3];
y = x.^3-3*x.^2+2*x+1;
plot(x,y,'r')
grid on
title('Graph of x^3-3*x^2+2*x+1')
xlabel('x')
ylabel('y')
It is strongly recommended to start all scripts with an instruction clear all, which cancels the
values of all variables defined before the script execution. The command format can be used
instead to specify which format should be employed for the representation of real numbers. In the
exercises of this course it is always recommended to use the format long instruction at the
beginning of each script. It is also recommended to close any graphical window that may have been
opened before. Therefore, a prototype script for this course should begin with the instructions
clear all
close all
format long
The most recent Matlab versions also allow for subdivision of a script in sections and for a more
advanced format called live script, which allows to combine code and text. However, sections and
live scripts will not be required for the solution of the exercises of this course. Interested students can
learn about sections and live scripts in the Matlab documentation.
Exercise 5
Write a script to plot on the same graphical window the graphs of
on the interval in red, green and black colors, respectively, with the title Trigonometric
polynomials. Use the command help to know more about the options of the command plot.
Exercise 6
Write a script to plot on the same graphical window the graph of
in these different forms
computed at and displayed as blue circles
computed at and displayed as a continuous black line.
Functions
In addition to the predefined Matlab functions, it is possible to define new functions that take as input
arguments one or more variables and return the evaluation of the function. Let us consider for
example the function and suppose that we want to evaluate this function on the vector
There are several different ways to define this function in Matlab. Here we will focus
only on two main possibilities. The first and most widely used for fast definition of simple function is
through the function handle operator defined by the command @, that can be used to create an
anonymous function as follows
x = [0:1:3]';
f = @(x) x.^3 - 1;
y = f(x)
t = [4 5];
z=f(t)
This definition can be extended to the case of vector valued functions and functions of more than one
variable, as for example the function
In this case we can proceed as follows:
g = @(x,y) [x + y; x - y];
Suppose now that we want to define the function that is, we want to fix the value of
as a parameter. We can write in this case
x=1;
h = @(y) g(x,y);
or more directly
h = @(y) g(1,y);
and define in such a way a new function of the variable y only. As all the functions in Matlab, the
functions and h can be evaluated on vectors and matrices. We have to be careful in the
definition of functions that contain componentwise operations. For example the functions
f = @(x) x.^2;
g = @(x) x^2;
define two different functions, the second of which will only execute correctly for square matrices.
Another possibility to define a new function in Matlab is by including the function in an external m-file.
For example, the same function can be defined creating an m-file called fun.m that
contains the commands
function y = fun(x)
y = x.^3 - 1;
end
This function can be evaluated in the vector by calling the function in the command
window as
y = fun(x)
Notice that, for this to work, the file fun.m must be placed in the same directory from which the
command line is executed and in the statement
function y = fun(x)
one must use the same function name (fun in this case) used to name the corresponding m-file. To
define the vector valued function we can create instead for example a file fun2.m of content
function z = fun2(x,y)
z = zeros(2,1);
z(1) = x + y;
z(2) = x - y;
end
If we need to use the function fun2 as an argument for another function (we will see some
application in next exercise sessions), we can use a function handle defined as
g=@fun2
After this, the fun2 is renamed g and can be invoked with both names.
Exercise 1
Define the following functions:
using both methods described above and evaluate them on the vectors and
.
Functions can also have more than one output. For example, the following function
function [xx,yy]= decompose(z)
xx=real(z);
yy=imag(z);
end
yields as output the real and imaginary part of the complex number z.
Exercise 2
Given a complex number whose polar representation is define
a function that computes its modulus and phase together.
There is a major difference in the conceptual role and use of functions and scripts in Matlab.
Functions are completely self contained, in the sense that, after the execution of a function, the
variables defined inside the function are erased and are not defined any more. The only results of a
function's action are the values assigned to the output variable (or variables, see below) of the
function itself. On the contrary, after a script has been executed, all the variables defined by the script
remain available, unless they are removed explicitly using a clear command.
As a consequence, a proper Matlab programming style consists in encapsulating each single (and
possibly complicated) specific task with a well defined set of outputs in a function and then writing a
script that calls these functions to produce a wider range of results.
Matlab programming
Matlab can be used to some extent as a structured programming language. Programming instructions
very similar to those in languages like C or Fortran are available.
Logical expressions
Logical expressions are usually placed within brackets to highlight the fact that they have a well
defined binary value, equal to 0 for false expressions and 1 for true expressions. For example
(3 > 2)
(pi < 2)
(4 > 2)+ (pi < 1)
A list of logical statements of common use is the following:
x == y is true if x=y, false otherwise
x~= y is true if x is not equal to y, false otherwise
x>y is true if x is larger than y, false otherwise
x>=y is true if x is larger or equal than y, false otherwise
x<y is true if x is smaller than y, false otherwise
x<=y is true if x is smaller or equal than y, false otherwise
Conditional expressions
The command if allows to execute parts of code if some logical conditions are verified. For example
the code
if (5 < 3)
disp('5 is lower than 3')
elseif (5 == 3)
disp('5 is equal to 3')
else
disp('5 is larger than 3')
end
only executes the last statement. The command for allows instead to define a cycle of repeated
operations, that can depend on a integer index:
a=pi;
for i = 1:10
b = a*i + 2
end
Notice that both if and for must be followed by an end instruction. Index values can also be in
decreasing order:
a=pi;
for i = 10:-1:1
b = a*i + 2
end
or can change with a given step
a=pi;
for i = 1:3:10
b = a*i + 2
end
or can be elements of a vector
a=pi;
k=[1:3:10];
for i = k
b = a*i + 2
end
Exercise 3
Compute for Add the terms of the sum in ascending order. Repeat the
computation in descending order. Repeat both computations for Compare the results with
the output of the command sum(1:n) and with the exact formula
The command for can be used when the number of repeated operations is known before starting
the cycle, but quite often this is not the case. In this case it is possible to use the command break,
which interrupts execution of a cycle or of an if block, letting the script execution continue from the
first line after the end instruction. For example, suppose that we want to compute
until the sum is larger or equal than 100 and we want to know the value of n for which this happens.
We can proceed as follows:
maxnumber=1000;
s=0;
for i=1:maxnumber
s=s+i;
if(s>=100)
break
end
end
An alternative is to implement a similar cycle with the command while. The operations inside the
while cycle are only executed if some conditions are verified at each iteration. In this case we can
proceed as follows:
s=0;
n=0;
while (s <= 100)
n = n + 1;
s = s + n;
end
The command continue allows instead to pass control to the next iteration of a for or while loop
and skip all the instructions until the following end instruction, resuming the cycle execution for the
next value of the integer index defining the cycle. For example, suppose one wants to compute the
sum of all the even numbers smaller or equal than 100. This can be done with the following code:
s=0;
for i=1:100
if mod(i,2)==0
s=s+i;
else
continue
end
end
Exercise 4
Check that the above code is correct by comparing with the results obtained with an appropriate use
of the command sum.
Exercise 5
Compute for in two different scripts, using respectively a for and a while cycle.
Add the terms of the sum in ascending order. Repeat the computation in descending order. Repeat
both computations for Compare the results with those obtained with an appropriate use of
the command sum and with the exact formula
Exercise 6
Write a MATLAB function that builds the Hilbert matrix, whose components are
Compare the result with the output of the MATLAB function hilb.
Two dimensional plots
The graphs of functions of two variables can be plotted in MATLAB in several ways, we will introduce
only one basic possibility that uses two dimensional arrays of coordinates at which a function is
evaluated. More specifically, given two row (or column) vectors , the
command meshgrid(x,y) builds two arrays with m rows and n columns that contain respectively
the x and y coordinates of the points For example
x=[1:4];
y=[-1:1];
[X,Y]=meshgrid(x,y)
builds two matrices X,Y. X contains copies of on each row and Y contains copies of on
each column. These matrices can be used to compute values of functions of two variables at
the points For example,
x=[0:0.1:4];
y=[-1:0.1:1];
[X,Y]=meshgrid(x,y);
f=@(x,y) sin(x).*cos(2*y);
Z=f(X,Y);
builds a matrix Z containing the values of fat the points with coordinates Functions
evaluated in this way can be represented graphically with various specific MATLAB commands. The
command surf plots the graph in three-dimensional space. The command contour plots instead
some of the function level sets (or contour lines(, that is, curves in the plane over which the
function has a constant value. The contour lines to be plotted can be specified by the user as in the
following example
x=[0:0.1:2*pi];
y=[-pi:0.1:pi];
[X,Y]=meshgrid(x,y);
f=@(x,y) sin(x).*cos(2*y);
Z=f(X,Y);
figure(1)
surf(X,Y,Z)
figure(2)
v=[-0.8, -0.3,-0.1,0,0.1 0.3,0.8];
contour(X,Y,Z,v)
Notice that the elements in the vector v must be ordered from the smallest to the largest. The
command contour colours the contour lines using a color code that can be set by the user with the
command colormap. The spaces between the contours are left in white. The command contourf
plots instead the contours in black and fills the spaces between the contours with colours that depend
on the colormap. The color code can be displayed in the figure using the colorbar command, as in
the following example
x=[-2:0.1:2];
y=[-2:0.1:2];
[X,Y]=meshgrid(x,y);
f=@(x,y) 2*exp(-X.^2-2*Y.^2);
Z=f(X,Y);
figure(1)
surf(X,Y,Z)
figure(2)
v=[0,0,0001,0,001,0.05,0.1,0.3, 0.4,0.6,0.8,1];
colormap('copper')
contourf(X,Y,Z,v)
colorbar