Introduzione a MATLAB Paolo Valigi
Dipartimento di Ingegneria Università degli Studi di Perugia
2 MATLAB - Basic
Credits
Based on material from the net, and in particular:
• Sergio Bittanti, Politecnico di Milano (Technical University of Milan)
• Ashok Krishnamurthy, Ohio Supercomputer Center
3 MATLAB - Basic
Table of Contents
• Overview • Basic Interfaces • Arrays, Matrices, Operators • Programming • Data I/O
• Basic Data Analysis • Numerical Analysis • Graphics, Data Visualization, Movies • Inter-language Programming
Overview
5
MATLAB
• “MATrix LABoratory” • Powerful, extensible, highly integrated
computation, programming, visualization, and simulation package
• Widely used in engineering, mathematics, and
science
6 MATLAB - Basic
MATLAB System
• Language: arrays and matrices, control flow, I/O, data structures, user-defined functions and scripts
• Working Environment: editing, variable management, importing and exporting data, debugging, profiling
• Graphics system: 2D and 3D data visualization, animation and custom GUI development
• Mathematical Functions: basic (sum, sin,…) to advanced (fft, inv, Bessel functions, …)
• API: can use MATLAB with C, Fortran, and Java, in either direction
7 MATLAB - Basic
Online MATLAB Resources
• www.mathworks.com/• http://it.mathworks.com/academia/student_center/tutorials/launchpad.html
• https://www.youtube.com/watch?v=QOJCvHUkJSs
• http://www.uniroma2.it/didattica/CMCA3/deposito/MATLAB_base.pdf
• …. mille altre fonti e pagine
Basic Interfaces
9 MATLAB - Basic
Main MATLAB Interface
10 MATLAB - Basic
MATLAB Editor Window
11 MATLAB - Basic
MATLAB Help Window (Very Powerful)
12 MATLAB - Basic
Command-Line Help �: List of MATLAB Topics
>> help HELP topics: matlab\general - General purpose commands. matlab\ops - Operators and special characters. matlab\lang - Programming language constructs. matlab\elmat - Elementary matrices and matrix manipulation. matlab\elfun - Elementary math functions. matlab\specfun - Specialized math functions. matlab\matfun - Matrix functions - numerical linear algebra. matlab\datafun - Data analysis and Fourier transforms. matlab\polyfun - Interpolation and polynomials. matlab\funfun - Function functions and ODE solvers. matlab\sparfun - Sparse matrices. matlab\scribe - Annotation and Plot Editing. matlab\graph2d - Two dimensional graphs. matlab\graph3d - Three dimensional graphs. matlab\specgraph - Specialized graphs. matlab\graphics - Handle Graphics. …etc...
13 MATLAB - Basic
Command-Line Help �: List of Topic Functions
>> help matfun Matrix functions - numerical linear algebra. Matrix analysis. norm - Matrix or vector norm. normest - Estimate the matrix 2-norm. rank - Matrix rank. det - Determinant. trace - Sum of diagonal elements. null - Null space. orth - Orthogonalization. rref - Reduced row echelon form. subspace - Angle between two subspaces.
…
14 MATLAB - Basic
Command-Line Help �: Function Help >> help det DET Determinant. DET(X) is the determinant of the square matrix X. Use COND instead of DET to test for matrix singularity. See also cond. Overloaded functions or methods (ones with the same name in other directories)
help laurmat/det.m Reference page in Help browser doc det
15 MATLAB - Basic
Keyword Search of Help Entries
>> lookfor who newton.m: % inputs: 'x' is the number whose square
root we seek testNewton.m: % inputs: 'x' is the number whose
square root we seek WHO List current variables. WHOS List current variables, long form. TIMESTWO S-function whose output is two times its
input. >> whos Name Size Bytes Class Attributes ans 1x1 8 double fid 1x1 8 double i 1x1 8 double
Variables (Arrays) and Operators
17 MATLAB - Basic
Variable Basics
no declarations needed
mixed data types
semi-colon suppresses output of the calculation’s result
>> 16 + 24 ans = 40 >> product = 16 * 23.24 product = 371.84 >> product = 16 *555.24; >> product product = 8883.8
18 MATLAB - Basic
MATLAB Data •
The basic data type used in MATLAB is the double precision array • No declarations needed: MATLAB automatically allocates required memory • Resize arrays dynamically • To reuse a variable name, simply use it in the left hand side of an assignment statement • MATLAB displays results in scientific notation
o Use File/Preferences and/or format function to change default § short (5 digits), long (16 digits) § format short; format compact
19 MATLAB - Basic
Vectorization Example*
>> type slow.m tic; x=0.1; for k=1:199901 y(k)=besselj(3,x) + log(x);
x=x+0.001; end toc; >> slow Elapsed time is 21.861525 seconds. *times measured on this MacBook
>> type fast.m tic; x=0.1:0.001:200; y=besselj(3,x) + log(x); toc; >> fast Elapsed time is 0.216881 seconds. Roughly 100 times faster without use of for loop
20 MATLAB - Basic
More Matrix Math in MATLAB
• det(A): computes determinant • inv(A): computes inverse • expm(A),logm(A), sqrtm(A):
computes exponential, logarithm and square root of A
• polyvalm(p,A): evaluate matrix
polynomial, p(A). • lscov(A, b, V): computes least
square solution with known covariance
• lsqnonneg(A,b): non-negative least squares
• norm(A): computes matrix norm • orth(A), null(A): finds a
basis for the range and null space of A
• qr(A): orthogonal-triangular
decomposition of A • subspace(A,B): computes angle
between subspaces defined by A and B
21 MATLAB - Basic
Multidimensional Arrays >> r = randn(2,3,4) % create a 3 dimensional array filled with normally distributed random numbers r(:,:,1) =
-0.6918 1.2540 -1.4410
0.8580 -1.5937 0.5711
r(:,:,2) =
-0.3999 0.8156 1.2902
0.6900 0.7119 0.6686
r(:,:,3) =
1.1908 -0.0198 -1.6041
-1.2025 -0.1567 0.2573
r(:,:,4) =
-1.0565 -0.8051 0.2193
1.4151 0.5287 -0.9219
randn(2,3,4): 3 dimensions, filled with normally distributed random numbers
“%” sign precedes comments, MATLAB ignores the rest of the line
22 MATLAB - Basic
Colon Operator (Vector Creation) >> 1:5 % use the colon operator to create row vectors ans = 1 2 3 4 5 >> 1:0.9:6 % you can vary the increment (0.9 in this
case) ans = 1.0000 1.9000 2.8000 3.7000 4.6000
5.5000
The last element is always less than or equal to the upper
limit
23 MATLAB - Basic
The “Dot Operator” • By default and whenever possible MATLAB will
perform true matrix operations (+ - *). The operands in every arithmetic expression are considered to be matrices.
• If, on the other hand, the user wants the scalar version of an operation a “dot” must be put in front of the operator, e.g., .*. Matrices can still be the operands but the mathematical calculations will be performed element-by-element.
• A comparison of matrix multiplication and scalar multiplication is shown on the next slide.
24 MATLAB - Basic
Easy 2-D Graphics
>> x = [0: pi/100: pi]; % [start: increment: end] >> y = sin(x);
>> plot(x,y), title('Simple Plot')
Programming
26 MATLAB - Basic
• MATLAB m-file Editor – To start: click icon or enter edit command in
Command Window, e.g., >> edit test.m • Scripts and Functions • Decision Making/Looping
– if/else – switch – for and while
• Running Operating System Commands
Outline
27 MATLAB - Basic
You can save and run the file/function/script in one step by clicking here
Tip: semi-colons suppress printing, commas (and semi-colons) allow multiple commands on one line, and 3 dots (…) allow continuation of lines without execution
m-file Editor Window
28 MATLAB - Basic
Scripts and Functions
• Scripts do not accept input arguments, nor do they produce output arguments. Scripts are simply MATLAB commands written into a file. They operate on the existing workspace.
• Functions accept input arguments and produce output variables. All internal variables are local to the function and commands operate on the function workspace.
• A file containing a script or function is called an m-file • If duplicate functions (names) exist, the first in the
search path (from path command) is executed.
29 MATLAB - Basic
function [a b c] = myfun(x, y) b = x * y; a = 100; c = x.^2; >> myfun(2,3) % called with zero outputs ans = 100 >> u = myfun(2,3) % called with one output u = 100 >> [u v w] = myfun(2,3) % called with all outputs u = 100 v = 6 w = 4
Functions – First Example Write these two lines to a file myfun.m and save it on MATLAB’s path
Any return value which is not stored in an output variable is simply discarded
30 MATLAB - Basic
Function Syntax Summary • If the m-file name and function name differ, the file
name takes precedence • Function names must begin with a letter • First line must contain function followed by the most
general calling syntax • Statements after initial contiguous comments (help lines)
are the body of the function • Terminates on the last line or a return statement
31 MATLAB - Basic
if/elseif/else Statement >> A = 2; B = 3; >> if A > B 'A is bigger' elseif A < B 'B is bigger' elseif A == B 'A equals B' else error('Something odd is happening') end ans = B is bigger
32 MATLAB - Basic
switch Statement
>> n = 8 n = 8 >> switch(rem(n,3)) case 0 m = 'no remainder' case 1 m = ‘the remainder is one' case 2 m = ‘the remainder is two' otherwise error('not possible') end m = the remainder is two
33 MATLAB - Basic
for Loop >> for i = 2:5
for j = 3:6
a(i,j) = (i + j)^2
end
end
>> a
a =
0 0 0 0 0 0
0 0 25 36 49 64
0 0 36 49 64 81
0 0 49 64 81 100
0 0 64 81 100 121
34 MATLAB - Basic
while Loop
>> b = 4; a = 2.1; count = 0; >> while b - a > 0.01 a = a + 0.001; count = count + 1; end >> count count = 1891
35 MATLAB - Basic
MATLAB’s Search Path
• Is name a variable?
• Is name a built-in function?
• Does name exist in the current directory?
• Does name exist anywhere in the search path?
• “Discovery functions”: who, whos, what, which, exist, help, doc, lookfor, dir, ls, ...
Data I/O
37 MATLAB - Basic
Loading and Saving Workspace Variables
• MATLAB can load and save data in .MAT format
• .MAT files are binary files that can be transferred across platforms; as much accuracy as possible is preserved.
• Load: load filename OR A = load(‘filename’)
loads all the variables in the specified file (the default name is MATLAB.MAT)
• Save: save filename variables saves the specified variables (all variables by default) in the specified file (the default name is MATLAB.MAT)
38 MATLAB - Basic
ASCII File Read/Write
load and save can also read and write ASCII files with rows of space separated values: • load test.dat –ascii
• save filename variables (options are ascii, double, tabs, append)
• save example.dat myvar1 myvar2 -ascii -double
Basic Data Analysis
40 MATLAB - Basic
Basic system analysis
• Basic, and more advanced, systems analysis is easily accomplished in MATLAB.
• Remember that the MATLAB default is to
assume variables are matrices.
41
To describe a continuous time system, the ss command (state space) is available
dx/dt=Ax(t)+Bu(t) y(t)=Cx(t)+Du(t) >>system=ss(A,B,C,D)[ss(A,B,C,0)];
as well as the tf command (transfer function)
W(s) = num(s)/den(s) >>system_5=5(num,den);
Similar commands for discrete time and sampled-data system
Basic system analysis (2)
42
• Impulse response: – impulse(system) – Impulse(system_tf)
• Step response: – step(system) – step(system_tf)
• Response to a generic input signal: – [y,t,x] = lsim(system,u,t,x0)
• Frequency response:
– Bode(system)
Basic system analysis (3)
Numerical Analysis
44 MATLAB - Basic
Solving Linear Equations
Consider the set of equations Ax = b • A is an n x m matrix, x is an m x 1 vector and b is
an n x 1 vector • The rank of a matrix is the number of independent
rows (or columns). Rank can be checked using the MATLAB command rank
• Equations are
• consistent if rank(A) = rank([A b]) • independent if rank(A) = n
Existence of solution
Uniqueness of solution
45 MATLAB - Basic
Ordinary Differential Equations
• MATLAB has a collection of m-files, called the ODE suite to solve initial value problems of the form
M(t,y)dy/dt = f(t, y)
y(t0) = y0
where y is a vector.
• The ODE suite contains several procedures to solve
such coupled first order differential equations.
46 MATLAB - Basic
Steps in ODE Solution Using MATLAB • Express the differential equation as a set of first-order ODEs
M(t,y)dy/dt = f(t,y)
• Write an m-file to compute the state derivative function dydt = myprob(t, y)
• Use one of the ODE solvers to solve the equations
[t, y] = ode_solver(‘myprob’, tspan, y0);
Time index
Solution matrix
ODE solver
ODE file for
derivatives
Solution time span
[t0 tf]
Initial conditions
47 MATLAB - Basic
ODE Suite Solvers
• ode23: explicit, one-step Runge-Kutta low-order solver
• ode45: explicit, one-step Runge-Kutta medium order solver. First solver to try on a new problem
• ode113: multi-step Adams-Bashforth-Moulton solver of varying order
• ode23s: implicit, one-step modified Rosenbrock solver of order 2
• ode15s: implicit, multi-step numerical differentiation solver of varying order. Solver to try if ode45 fails or is too inefficient
Non-stiff equations Stiff equations
48 MATLAB - Basic
Example : van der Pol Equation
• Equation is d2x/dt2 - µ(1-x2)dx/dt + x = 0 • Convert to first order ODEs
using y1 = x, y2 = dx/dt
dy1/dt = y2
dy2/dt=µ(1-y12)y2-y1
function dydt = vdpol(t,y)
%
% van der Pol equation
mu = 2;
dydt = [y(2);mu*(1- … y(1)^2)*y(2)-y(1)];
ODE File vdpol.m
49 MATLAB - Basic
van der Pol Equation Solution >> tspan = [0 20]; >> y0 = [2; 0]; >> [t, y] = ode45('vdpol', tspan, y0); >> plot(t, y(:,1), t, y(:,2), '--');
50 MATLAB - Basic
More on ODE Solvers
• There are a number of different options in specifying the ODE file. Check HELP on odefile for details.
• odeset and odeget can be used to set and examine
the ODE solver options. • Can find events (such as max/min/zero, crossings etc.)
in the solution.
Graphics, Data Visualization & Movies
52 MATLAB - Basic
Overview
• Plots – Simple plots – Subplots (Multiple Axis Regions) – Mesh plots (Colored wire-frame view of surface) – Surface Plots – Patches – Contour Plots – Visualization
• Images – Indexed images – Intensity images – Truecolor images – Reading and writing images
• Movies
53 MATLAB - Basic
Basic XY Plot
>> x = [0:pi/100:pi];
>> y = sin(x);
>> plot(x,y), title('Simple Plot')
54 MATLAB - Basic
Multiple Curve Plots
Line color, style, marker type, all within single quotes
>> z = cos(x);
>> plot(x,y,'g.',x,z,'b-.'), title('More Complicated')
55 MATLAB - Basic
Plot Power: Contour & 3-D Mesh
To save:
print -djpeg myfigure.jpg
use help print for options
>> t = 0:pi/25:pi; >> [x,y,z] = cylinder(4*cos(t));
>> subplot(2,1,1)
>> contour(y)
>> subplot(2,1,2)
>> mesh(x,y,z)
>> xlabel('x')
>> ylabel('this is the y axis')
>> text(1,-2,0.5,...
'\it{Note the gap!}')
56 MATLAB - Basic
Subplots
Used to display multiple plots in the same figure window, subplot(m,n,i) subdivides the window into m-by-n subregions
(subplots) and makes the ith subplot active for the current plot
>> subplot(2,3,1) >> plot(t, sin(t), 'r:square') >> axis([-Inf,Inf,-Inf,Inf]) >> subplot(2,3,3) >> plot(t, cos(t), 'g') >> axis([-Inf,Inf,-1,1]) >> subplot(2,3,5) >> plot(t, sin(t).*cos(t), 'b-.') >> axis([-Inf,Inf,-Inf,Inf])
4 5 6
2
3 1
57 MATLAB - Basic
Surface Plots
• surf(Z) generates a colored faceted 3-D view of the surface. – By default, the faces are quadrilaterals, each of constant color,
with black mesh lines – The shading command allows you to control the view
>> figure(2); >> [X,Y] = meshgrid(-16:1.0:16); >> Z = sqrt(X.^2 + Y.^2 + 5000); >> surf(Z)
>> shading flat
>> shading interp
Default: shading faceted