1 - Intro Matlab
1 - Intro Matlab
Organization of
the course Learning objectives:
Model/software management
Autonomous programming
Introduction to programming languages (1/5)
Why «languages»?
• Because it is a way to communicate to the computer what it has to
do.
• Keywords are special words which correspond to specific
operations.
• Data are needed as well.
• The way in which the instructions are put together has the same
structure of a language (syntax, spelling).
What is a program?
• It is a set of instructions targeted to reach a result
Matlab example:
VBA: d=10;b=5;c=3;
d=10;b=5;c=3;
if (d>b) then
if (d>b) c=10;
c=10; End If
end
(d>b) is the condition.
if and end (Matlab) (or End If (VBA) and Then (VBA) are keywords.
The spelling is relevant.
All the instruction between if and end (Matlab) or End If (VBA) are
executed only if the condition is true.
In the Example, if d>b (which happens with d=10 and b=5), then c is
set equal to 10. Otherwise, c would have remained equal to 3.
Introduction to programming languages (4/5)
Matlab Example:
d=10;b=5;c=3;
if (d>b)
c=10;
end
In the example
➢if the value contained in d is greater than the value contained in b
(which is verified with the assigned values of b and d) then c is
assigned the value 10.
➢otherwise c would have remained equal to 3.
Introduction to programming languages (5/5)
•Example:
MATLAB saves statements that run in the Command Window to the history file History.xml. These statements include those you run using
the Evaluate Selection item on context menus in tools such as the Editor, Command History window, and Help browser. By default,
MATLAB automatically saves the command history file after each statement. The history file does not include every action taken in
MATLAB. For example, changes to values in the Variables editor are not included in the Command History window. All entries remain
until you delete them, or until the number of statements in the history file exceeds the number of statements to save, as specified in the
Command History preferences. When the specified limit is reached, MATLAB automatically deletes the oldest entries. By default, the
Command History window saves 25,000 statements.
The Current folder
Lists the files in the current directory.
Automatically, Matlab is placed on the directory Documenti/Matlab.
The files should all be saved there.
MATLAB INTERFACE
My folder
Documenti / Matlab
The editor
Steps to follow:
Write the program in the editor
Save with Save as giving a name (I
gave ScriptIf)
Run with Run (does not run if you
have not given the name, but notifies
you)
If the editor is not open you can open it by clicking on "New / script": in the editor you
open a program (untitled, name that you can change), the program written in the editor
and active (you may have written many programs) is run by clicking on the green arrow.
Alternatively, you can run a script by typing the name of the file on the command line.
Problem: How to use already calculated values?
MATLAB does not allow you to modify commands that have already been
executed.
These can be called up on the command line by pressing 'up arrow' several
times, or by clicking on the relevant command in the 'Command history'
window (if it appears);
Or, if you think that a value serves later you can store it in a variable that
you can easily recall:
Instructions typed
by the user
Remark: there are rules for writing variable names: Cannot contain
special characters (?,!,$,%,*, spazi intermedi, ecc.) and they can't start
with a number.
A. floating-point notation
B. exponential notation:
or format short e
Exercise Type on the command line >>
pi
format long
pi
format short
pi
format long e
pi
format short e
pi
Script files
>>5*2^3-1
and
>>(5*2)^(3-1)
Vectors and Matrices
The mathematical structure on which Matlab is based is the matrix: in Matlab
even a scalar is a matrix... size 1x1.
It is no coincidence that Matlab is the short for MATrix LABoratory.
For example, typing x = 2.45, we have declared the variable x and we assigned it
the value 2.45.
the omission of the semicolon means that the contents of the variable are viewed
on the screen x.
Matlab only manipulates matrices, and in fact an inspection at the Workspace
reveals that x is an array of size 1x1.
Row vector (any length)
It starts with an open square bracket and ends with a
closed square bracket.
Elements are separated either with gaps or with
commas.
Example
>>[ 1 2 3 4];
>>[1,2,3,4];
They are the same row vector. to store it in the v
variable type
>> v=[1 2 3 4];
For example
v(1)=100
disp(v)
100 20 30 40 50
A=
123
456
789
Other ways of assigning an array
>>A=[1 2 3; 4 5 6; 7 8 9]
>>A=[1, 2, 3; 4 , 5 , 6; 7 , 8, 9]
>> A=[1, 2, 3 space quantity
4, 5, 6 is not
7, 8, 9] important.
You always get the same result:
A=
1 2 3
4 5 6
7 8 9
Matrix Multiplication NOTE: the transpose of c is c’
!! Becomes 3x1
1x3*1x3 error ! Check the innersize of your matrix before executing!
2x3*3x1 ok !
Further instructions
Identity (identical) matrix order n
eye(n)
>>A = eye(3)
A=
100
010
001
Sub-matrix of the identical matrix
eye(n,m)
>>A= eye(2,3)
A= PAY ATTENTION
100 MATLAB DISTINGUISHES
010 UPPERCASE AND
LOWERCASE
Further instructions ZERO MATRIX ALL ZEROS
zeros(n)
>>A= zeros(3)
A=
0 0 0
0 0 0
0 0 0
VECTOR WITH COLUMN OF ZERO
zeros(n,1)
>>v=zeros(3,1)
v=
0
0
0
Further instructions
Construct a zero matrix anywhere and with the vector v
on the diagonal:
A=diag(v)
>>v=[1 2 3];
A= diag(v)
A=
100
020
003
oppure
A=diag([1 2 3]);
Definition of vectors.
4
6
Solve a linear system Ax=b
Case in which theorem and
Cramer's rule are valid: square
matrix, non-zero determinant
MATLAB explicitly calculate the
solution
X=inv(A)*b
Example:
A=[2 6; 4 3]; b=[3;1];
Calculation det(A), check that is
not zero, then I perform
x=inv(A)*b and get the result.
https://www.andreaminini.org/matematica/algebra-
lineare/teorema-di-cramer
ALWAYS ON VECTORS AND MATRICES
REMIND
The presence of a point among the vector and the operation to
be executed means that the operation is done on each single
component of the vector.
Example:
x=[1,2,3];
x.^2 gives [1,4,9]
But x^2 gives error because it tries to multiply a vector 1x3 by
a vector 1x3 (the number of columns of the I is different from
the number or rows of the II, so the product cannot be done).
https://www.mathworks.com/academia/tah-portal/luiss-31077355.html
Download Matlab from the Luiss website
Replicate all the examples, in case of doubt
write me to [email protected]
y=f(x)
y=f(x)
Input:
Output: results scope of the function
Functions M-file (Matlab files .m)
Input z=[1;2]
Output
Value of the first component of the vector:
f(z)=z’*V*z, with V=[ 1 2; 3 4];
Value of the second component of the vector:
f(z)=z(1)-exp(z(2));
f=[z’*V*z
z(1)-exp(z(2))];
Vectorial output
Example: write a function which gives:
I output: the same as before
II output: g(z)=z(1)-(z(2))^2;
Solution
function [f,g]=fun(z)
f=[z’*V*z
z(1)-exp(z(2))];
g=[z(1)-(z(2))^2];
Figure
(2D, 3D, vertical section)
Plot 2D
Plot 3D
Restriction
Histograms
Figure
(2D, 3D, vertical section)
Plot 2D
Plot 3D
Restriction
Histograms
2D Figures
Couples of coordinates are needed.
Example:
x=1:1:10;
y=x.^2; %square of each component
plot(x,y);
Further parameters for plot: color
The first letter of the english name of the color is used (apart
from black, for which the letter is k, so to avoid overlaps with
blue)
Examples: type
plot(x,y, 'k'); %black
plot(x,y, 'b'); % blu
plot(x,y, 'y'); %yellow
plot(x,y, 'r'); %red
plot(x,y, 'm'); %magenta
plot(x,y, 'g'); %green
Further parameters for plot: line
-Continuous line
: dotted line
.- alternating dot and line
It can be combined with the color code.
Examples
plot(x,y,’k-’); %black with continuous line
plot(x,y,’r:’); %red with dotted line
plot(x,y,’g.-’); %green with dot-line pattern
Plot of more functions in the same draw
Two ways:
1) Write «hold on» between the plots. It is sufficient to write it
one time. To stop its effect it is sufficient to type «hold off»
Example:
plot(x,y, 'k'); %black
hold on
plot(x,x.^3,’r’);
plot (x,1./x,’g’);
hold off
2) Couples of coordinates into the same instruction plot.
Example:
plot(x,y,'k’,x,x.^3,’r’,x,1./x,’g’);
Plot of more functions in the same draw
Example:
x=1:1:10;
Y=x.^2; %square of each component
plot(x,y,'k‘,x,x.^3,’r’,x,1./x,’g’);
Histograms
Hist counts how
many values fall in
the bins.
v=[5 5 1 2 5 1 2 3 7 5 6 9 10];
[y,x]=hist(v)
bar(x,y/sum(y))
More data = better histogram
v=randn(10,1);
[y,x]=hist(v);
bar(x,y/sum(y))
v=randn(100000,1);
[y,x]=hist(v);
bar(x,y/sum(y))
3 D graphs
Matlab needs a grid to plot the surface. Example:
Given x = [-1:0.1:1] and y=[0:0.1:2];
Build the grid through meshgrid:
Exercise: type
[X,Y,Z] = peaks(30);
surfc(X,Y,Z)
colormap hsv
Insert labels on the axes
Another example
Draw contour lines
Example:
x = [-2:0.1:2]
y = [-2:0.1:2]
[X,Y] = meshgrid (x,y)
f = (X.^2+Y.^2)+5
surfc (X,Y,f)
Rotate the 3D figures
Try the icons
rotate
Color palette
(color palette) through colormap. Example:
colormap(jet)
x=[-1:0.1:1];
y=[0:0.1:2]; 1
[X,Y]=meshgrid(x,y);
0.8
0.6
0.4
f=exp(-(X.^2+Y.^2));surf(X,Y,f)
0.2
0
2
1.5 1
1 0.5
0
0.5 -0.5
0 -1
colormap(gray)
x=[-1:0.1:1]; 1
y=[0:0.1:2];
0.8
0.6
0.4
[X,Y]=meshgrid(x,y);
0.2
0
2
1.5 1
1 0.5
f=exp(-(X.^2+Y.^2));surf(X,Y,f)
0
0.5 -0.5
0 -1
73
76
Restrictions to a vertical plot
Not for all the x, but only for a specific value of x. Unfortunately, we
cannot just use 1 value, but we need to replicate the value as many times
as the length of the vector of y:
f = exp(-X.^2-Y.^2); 0.2
surf(X,Y,f) 0.1
0
2
1 0
0 -0.5
-1
-1 -1.5
-2 -2