You are on page 1of 69

Matlab

Overview

Matlab is a SW designed for the numerical calculation on scientific


and engineering applications.

Web site http://www.mathworks.com/

The main Matlab functions are the following:


1) Plot 2D and 3D ;
2) Linear Algebra ;
3) Interpolation and approximation ;
4) ODE and PDE solution ;

How to run matlab on linux OS?

To run matlab in your linux/unix OS we have follow these steps:


1) Open a new terminal
2) type cd /home/Matlab_folder
3) type ./bin/matlab
After these 3 steps we should have a screenshot like the
following

Matlab Prompt

Help

To obtain information about Matlab commands select help in the main


menu as in the following screenshot

Help

On search area you can enter the command that we need information
and get syntax, parameters, input and / or output etc.. etc..

For example, writing the command '"plot" you will get information on that
command. In particular, on the left column will be all the items of the
manual where there is information about "plot", clicking on one of these
items you will get the information about the selected item and the right
column .

Help Matlab example

Variables

In general on Matlab we can define variables, functions and


programs. The generic variable will be defined as follows:
variable_name = instruction ;
where the output of the instruction is assigned to variable_name ;
Each variable must be identified with an alphanumeric string that can
not start with a number and can not contain special characters (eg:
var01 is a valid name 01 * var is not a invalid name). You have to
pay attention to the fact that the variable name is case sensitive so
you do not confuse the uppercase and lowercase.

Variables

On Matlab should not be defined the type and the size of the variable
before use it (opposite in C, C++, Fortran);
To view and edit a variable is available in the graphical user interface
the Workspace;
Each variable is added to the Workspace after the definition;
Each variable can be deleted from the workspace with the command
--> clear variable_name;
The command "clear all" allows to delete all the variables created by
a single user, however, it strongly discouraged the use of this
command inside a script (with the exception of line 1) because it can
destroy all the defined variables .

Variables and workspace

Variables examples

Example: Create a variable named "var" and assign it the value 2.


Check the result using the Workspace.
Commands :
var=2;

We create the variable and we assign it the value 2

The variable var will appear on the Workspace in the list of


variables.

Variables examples

Format

In Matlab, we can choose the format in which numbers represent the


variables values using the command "format".
To use this command we must be respected the following syntax:
format type ;
format;
Where:
format by itself specifies the default display type, format short (that
is, 5-digit scaled, fixed-point values).
format type changes the format to the specified type.

Format
short (default) Scaled fixed-point format, with 4 digits after the
decimal point. For example, 3.1416.
long Scaled fixed-point format with 15 digits after the decimal point
for double; and 7 digits after the decimal point for single. For
example, 3.141592653589793.
shortE Floating-point format, with 4 digits after the decimal point. For
example, 3.1416e+000.
longE Floating-point format, with 15 digits after the decimal point for
double; and 7 digits after the decimal point for single. For example,
3.141592653589793e+000.
For more information check Matlab Help

Costants

In Matlab, there are some constants that are always available in the
workspace. To call these constants we must follow the following
syntax:
costant_name
Some constants available on Matlab are the following:
1) pi = 3.1415927...
2) i
3) eps

Costant
Imaginary unit
Floating-point relative accuracy
(releted to the machine used)

4) inf
5) nan

Infinity
NotANumber

Matrices and arrays

To define a matrix/array in Matlab we must follow the following


syntax:
A=[a b c; d e f ; g h i ]
Through this command we will get a 3x3 matrix where rows will be (a,
b, c), (d, e, f) and (g,h,i). In general, to write an array/matrix we
should follow the following rules :
1) The elements of a same row are separated by a comma or a
space;
2) Each row, except the last, must end with a semicolon;
3) The array elements must be enclosed in [ ] ;

4) Pay attention to the size of rows and columns pointing out that
the insertion is done by rows.

Matrices and arrays


Example: Define the matrix A in Matlab and extract the
element a11, the second row and the third column

1 6 9
A= 15 22 66
17 4 1

Matrices and arrays


To define the array we will use the following
instructions:
A=[1 6 9; 15 22 66 ; 17 4 1]
A(1)
A(2,:)
A(:,3)
The results are as follows.

Matrices and arrays

Matrices and arrays

An array of size "n" can be seen as a matrix composed of a single


row, then to define an array we can follow this syntax:

a=[a,b,c,d,e,.........,n];
In Matlab there are some commands that allow the insertion of
special matrices such as:
1) eye(n,n) ;
2) zeros(n,m);
3) ones(n,m);
4) triu(X,k);

5) tril(X,k);

Identity Matrix nxn


Matrix nxm all elements equal to zero
Matrix nxm all elements equal to one.
Upper triangular part of matrix part of matrix X
k = 0 is the main diagonal, k > 0 is above the main
diagonal, and k < 0 is below the main diagonal
part of matrix X
Lower triangular

Matrices and arrays

To get the elements of a matrix we must use the following


instructions:
A=[ a,b,c ; d,e,f ; g,h,i ];
b=A(i,j);

Generic matrix 3x3


The variable b will be equal to aij

In general it may be necessary get a row, a column or a part of them,


in this case we will have to use the symbol : as follow:
A(: ,1);
A(1, :);
A(1: 2,1);

We get the first column of the matrix A


We get the first row of the matrix A
We get the column array containing the first two
elements of the first column of the matrix A

Matrices and arrays

A useful command is the command "diag ()" it means you get a


column array containing the elements of the main diagonal of a
square matrix. Through this command you can build a square
diagonal matrix following the instructions:
b=[a,b,c];
C=diag(b);

C will be a 3x3 diagonal matrix where the


elements of the main diagonal are the elements
of the array b

To perform the inverse of a square matrix we can use the command


inv( A ) , whereas to get the transposed matrix we can use the
command A' .

Matrices and arrays

The sum of two matrices of the same size can be obtained through
the following statement:
A+B;
The product of two matrices of appropriate dimensions, is obtained by
the following statement:
A*B;

The exponential of a matrix A is obtained by the following statement:


expm( A ) ;
This statement must not be confused with exp (A) which perform the
exponential of the individual elements of the matrix.

Matrices and arrays

The determinant of a matrix A is obtained using the following


command:
det(A);

The rank of a matrix A can be calculated using the following


command:
rank(A);

Given two matrices A and B may be necessary to carry out the


multiplication (or division) 'element by element' in this context we
must use the commands ' .* ' , ' ./ ' e ' .^ ' (The last command
performs an element-by-element esponential).

Matrices and arrays


Example: define the matrix B in
matlab and calculate:

[ ]

1 0 0
B= 0 4 0
0 0 6

1) Determinant;
2) Rank;
3) Exponential matrix;
4) Esponential element-byelement;
5) Then extract the first row and
the second column.

Matrices and arrays


We will use the following commands:

d=[1,4,6]
B=diag(d)
det(B)
rank(B)
expm(B)
exp(B)
B(1,:)
B(:,2)

Note that expm (B) and exp (B) do not provide


in general the same results.

Matrices and arrays


The instruction expm(A) will perform the calculation of the following series :

e =
A

k =0

A
k!

In the case of diagonal matrices the series is equal to the following matrix:

a11

e
A
expm A=e = 0
0

0
e

a22

0
0
a33
e

Matrices and arrays


The instruction exp(A) performs the exponential element-byelement on the matrix A, for a diagonal matrix we obtain this result:

a11

e
exp A= e 0
0
e

][

a11

e
e
e
a22
0
e
e = 1
0
a33
e
e
1

1
1
a22
e
1
a33
1 e

Matrices and arrays

Matrices and arrays


The use of the command inv(A) can be dangerous when the matrix has
determinant close to zero. Below we report an example:

[ ]

1 2 3
A= 4 5 6
7 8 9
Using the command det(A) we get:
>>det(A)= 6.6613e-16

we can observe as det(A) is close to zero then the command inv(A) could
provide bad results.

Matrices and arrays


Exercize: define the matrix A and calculate the product A*inv(A).
We will get in this case after using the command B = inv (A) the following results
for the product A * B (theoretically equal to the identity matrix I):

0,25 1 0,25
AB= 2
4
1
4,25 7 1,75

This result is completely differenty from the theoretical so we have to be


very careful when we use the command inv (A)

Polynomial

The command "poly" is used to define a polynomial from its roots. :


Assuming that "a" and "b" are the roots of a generic second-order
polynomial, using the "poly" you will get the corresponding
polynomial
polynomial_name= poly( [a b]);

To calculate the roots of a polynomial, we can use the following


command:
roots( polynomial_name );

Mathematical Functions

round(x)

Round to nearest integer. Positive elements with a fractional part of


0.5 round up to the nearest positive integer. Negative elements with a
fractional part of -0.5 round down to the nearest negative integer. For
complex X, the imaginary and real parts are rounded independently.

fix(x)

Rounds the elements of x toward zero, resulting in an


array of integers. For complex x, the imaginary and real
parts are rounded independently.

floor(x)

Rounds the elements of x to the nearest integers less than or equal


to x. For complex x, the imaginary and real parts are rounded
independently.

ceil(x)

Rounds the elements of A to the nearest integers greater than or


equal to A. For complex A, the imaginary and real parts are rounded
independently.

sign(x)

Returns an array Y the same size as X, where each element of Y is:


1 if the corresponding element of X is greater than zero
0 if the corresponding element of X equals zero
-1 if the corresponding element
of X is less than zero

Matematical Functions

x=[-1.8 -0.1 3.4 5.6 7.0]

round(x) >> ans = -2

fix(x)

>> ans = -1

floor(x)

>> ans = -2

-1

ceil(x)

>> ans = -1

Mathematical Functions

abs(x)

returns an array Y such that each element of Y is the


absolute value of the corresponding element of X.

sqrt(x)

square root of x

exp(x)

exponential function

log(x) (or log10(x) logaritm in base e , 10 and 2


or log2(x))

Matehmatical Functions

sin(x)

Sine of argument in radians

cos(x)

Cosine of argument in radians

tan(x)

Tangent of argument in radians

cot(x)

Cotangent of argument in radians

asin(x)

Inverse sine; result in radians

acos(x)

Inverse cosine; result in radians

atan(x)

Inverse tangent; result in radians

acot(x)

Inverse cotangent; result in radians

sinh(x)

Hyperbolic sine of argument in radians

cosh(x)

Hyperbolic cosine of argument in radians

tanh(x)

Hyperbolic tangent
of argument in radians

For and While

In Matlab, we can define cycles For and While using the following
instructions:
for variable=values
statements 1;
....................;
statements n;
end

Sintax for instruction

while expression
comando 1;
..................;
comando n;
end

Sintax while instruction

If-Elseif-Else

The syntax for the instruction If-Elseif-Else is:


if expression 1
statemen 1;
..................;
statement n;
elseif expression 2
statement a;
..................;
statement z;
else
statement xa;
...................;
statement xz;
end;

Sintax If-Elseif-Else instruction

You can also use nested instructions


If-Elseif-Else.

Case

The syntax for the instruction Case is the following:


switch switch_expression
case case_expression
statement 1;
................. ;
statement n;
case case_expression
Sintax Case instruction
statement a;
..................;
statement z;
otherwise
statement;
end

Plot 2D and 3D
In Matlab to plot graphs must first open a graphics window, this is
done using the following command:
figure(num);
where the string 'num' is the number of the graphics window to be
opened and must be a natural number.
To clean the graphics window in use we must use the following
command:
clf(num);

Plot 2D and 3D

Plot 2D and 3D

To draw a 2D graph we can use the command 'plot', an example of


the use of this command is:
figure(1);
x=-1:0.1:1;
y=exp(x);
plot(x,y,'r'); grid
title(' Exponential function');
xlabel('x');
ylabel('y=exp(x)');
In particular, with these instructions we will get the graph of the
exponential function for x values between -1 and 1. The parameter 'r'
allows as to choose the color of the graph of the function (in this case
red), whereas the command 'grid' draws a grid on the graph. Finally,
the command 'title', 'xlabel' and 'ylabel' allows us to put a title for the
graph and labels on x and y axes.

Plot 2D and 3D

Plot 2D and 3D

To choice the graphics colors we can follow the following table:


k Black
b Blu
g Green
r Red
c Cyan
m Magenta
w White
y Yellow
Be careful avoid the use of white to draw a white line on a white
background ( invisible)

Plot 2D and 3D

Line Style Specifiers :


'-' Solid line (default)

'' Dashed line

':' Dotted line

'-.' Dash-dot line

'none' No line

Marker Specifiers :
'+' Plus sign

'o' Circle

'^' Upward-pointing triangle '.' Point

'x' Cross
(see matlab Help for more informations)

'*' Asterisk (not Asterix)

Plot 2D and 3D

plot(x,y,':*g'); grid

Plot 2D and 3D

Syntax to plot more functions in the same graph:


plot(x1,y1,'r*', x2,y2,'b-',........,xn,yn,'y');
Exercize: plot in the same graph the functions y=3*sin(pi*x) and
y=exp(-0.5*x) with x in [0,5]. Complete the graph with title, axes labels and grid.
clear all;
x=0:0.1:5;
y=3*sin(pi*x);
plot(x,y,'r'), xlable('x'), ylabel('y');grid
hold on
y1=exp(-0.5*x);
plot(x,y1,'g');
gtext('x1'); gtext('x2');gtext('x3'); gtext('x4');gtext('x5');gtext('x6'); Mouse placement of text in 2-D view

title('intersection graph functions y=3*sin(pi*x) and y1=exp(-0.5*x) ');

hold off

Plot 2D and 3D

Plot 2D and 3D

ezplot(fun)

plots the expression fun(x,y) over the default


domain -2 < x < 2 , -2 < y < 2 where
fun(x,y) is an implicit function.

Example:
clear all
clc
figure(1)
ezplot('x.^2-y.^4-1',[-4 4 -4 4]); grid
figure(2)

ezplot('cos(t)','sin(t)'); grid

Plot 2D and 3D

Plot 2D and 3D

Plot 2D and 3D

x=0.1:0.1:2;

subplot(m,n,p) divides the current


figure into
rectangular panes
that are numbered
rowwise.
Where m number of
rows ,n number of
columns ,p position
inside the matrix.

subplot(2,3,1) , plot(x,x,'r');grid
title('y=x');xlabel('x'); ylabel('y');
subplot(2,3,2), plot(x, x.^2,'b');grid
title('y=x^2');xlabel('x'); ylabel('y');
subplot(2,3,3), plot(x,sin(x),'y');grid
title('y=sin(x)');xlabel('x'); ylabel('y');

Example: plot in the same figure but in


different panes the functions:

subplot(2,3,4), plot(x,exp(x),'m');grid
title('y=exp(x)');xlabel('x'); ylabel('y');

y=x, y=x^2, y=sin(x), y=exp(x), y=log(x)


and y=cos(x).

subplot(2,3,5), plot(x,log(x),'g');grid
title('y=log(x)');xlabel('x'); ylabel('y');
subplot(2,3,6), plot(x,cos(x),'c');grid
title('y=cos(x)');xlabel('x'); ylabel('y');

Plot 2D and 3D

Plot 2D and 3D

To draw 3D graphs we can use the command 'surf' as follow:


figure(1);
x=-1:0.1:1;
y=x;
[X Y]=meshgrid(x,y);
Z=sin(X.^2+Y.^2);
surf(x,y,Z); grid
title(' Funzione Z=sin(X^2+Y^2)');
xlabel();
ylabel();
colorbar;
In particular, the command 'meshgrid' calculates all the possible
combinations for the values of
the arrays x and y to evaluate the
function Z. The command 'surf' deaws the graph for function Z giving
different colors to the chart depending
on the value of the function.

Plot 2D and 3D

Plot 2D and 3D

Exercize 1: plot the function


y=exp(x)*sin(x)

x=-1:0.1:1

blu line, ':' and marker 'o' title


axes and general title;

Exercize 2: plot the function


Z=(X^2+Y^2)*exp(X)
x=y=-1:0.1:1

with colorbar, asex labels and


title

Functions and Scripts

In Matlab we can write functions and scripts.


SCRIPT :
To make a script we can use any editor and we have to save the file
with an extension of type '.m'. However, there is on Matlab an editor
that can be activated by clicking the 'EDITOR' (notepad with pencil at
the top left). To run a script you would type the following statement:
file_name.m ;
A script can also be performed using ' Run under Debug menu ' on
Matlab Editor.

Functions and Scripts

Functions and Scripts

FUNCTION:
To create a function in Matlab, we can use a procedure similar to that
used in the script. The function must also follow the following
structure:
function[out1,........,outn]=function_name(input 1,.....,input n)
statement 1;
............... ;
statement n;
endfunction

Exercize Script

Exercize: write a script in Matlab to plot the


graph of the function z=y+exp(x) wher x = y are
in the interval [-2, 2].
Complete the graph with title, axes labels and
grid.

Exercize Script

After opening the matlab editor will insert the following instructions:
clear all;
clc;
x=-2:0.1:2;
y=x;
[X Y]=meshgrid(x,y);
Z=X+exp(Y);
figure(1)
surf(X,Y,Z); xgrid
title(' Z=X+exp(Y)');
xlabel('x');
ylabel('y');

Select Fileafter Save as and insert graf3.m and Save.

Exercize Script

Exercize Script

Select Debug Run from Matlab editor and wait results.

Exercize Script

Exercise: Write a Matlab script to calculate:


1) roots for the function y=x^2+3x-2.
2) plot the graph of the function y=x^2+3x-2 taking
care to be able to view the points of intersection with
the x-axis.
Complete the graph with title, axes labels and grid.

Exercize Script
clear all;
clc;
coef=[1,3,-2];
roots(coef)
x=-5:0.1:5;
y=x^2+3*x-2;
figure(1);
plot(x,y,'r');grid
title('Function y=x^2+3*x-2');
xlabel('x');

ylabel('y');

Esempi script

Roots x1= 0,5615528 x2= -3,5615528

Exercize Function

Exercise: Write a Matlab function able to calcuate the


sum of the elements of an array and save it as
sum_d.m. Then write a script test_sum.m able to
evaluate the correct operation of the function
sum_d.m and do the sum of the array elements for:

x=[1, 3, 4, 8, 2]

Eexrcize Function file sum.m


function [total]=sum_d(x)
[n]=size(x);
total=0;
for i=1:n(2)
total=total+x(i);
end
end

Exercize Function file sum_test.m


clear all;
clc;
x=[1,3,4,8,2];
total=sum_d(x)

And the result will be:


>>total=18

When you use the


functions pay attention
to the current folder !!!

You might also like