MMN - 02 - Intro Matlab
Numerical Methods and Modeling - 02
Introduction to Matlab (...)
Alexandre Pieri1 , Paolo Bardella2
1 Institute of the Atmospheric Sciences and Climate - CNR
2 Politecnico di Torino
[email protected]
[email protected]
[email protected]
MMN - 02 - Intro Matlab
Overview
1 Functions: plot, polynomials, integrals
2 Defining functions in files
3 Differential equations
MMN - 02 - Intro Matlab
Functions: plot, polynomials, integrals
Plan
1 Functions: plot, polynomials, integrals
2 Defining functions in files
3 Differential equations
MMN - 02 - Intro Matlab
Functions: plot, polynomials, integrals
Matlab contains several buil-in function such as sin(), cos(), exp(),
log(), sqrt()... What if you want to define your own function ?
What about polynomials ?
Handle functions offer a simple way to define functions that
combination of already defined functions.
Handle function: example
√
>>f=@(x)sqrt(x)*exp(x); % will define function f (x) = xex .
>>f(2) % should give ≈10.4497
>>u=(1:10);
>>f(u); % will not work, dimensions won’t match.
>>f=@(x)sqrt(x).*exp(x); % works.
MMN - 02 - Intro Matlab
Functions: plot, polynomials, integrals
Matlab allows to compute integrals of handle functions
integral: example
√
>>f=@(x)sqrt(x).*exp(x); % will defineRfunction f (x) = xex .
1√
>>If=integral(f,0,1) % computes If = 0 xex dx
We can also draw the curve Cf representing f on a defined interval
I = [a, b]
fplot: example
>>g=@(x)log(x)./(x.ˆ2+1); % will define function g(x) = log(x)x2 +1
.
>>fplot(g,[0 1],’ˆ’)
>>print -djpeg file % will save the current figure in jpeg format at
file.jpg.
MMN - 02 - Intro Matlab
Functions: plot, polynomials, integrals
Matlab define a polynomial of degree n by its n + 1 coefficients
ordered from the highest to the lowest exponent. Once they are
defined, the command polyval allows to evaluate the polynomial at
a given point.
polyval: example
>>p=[1 3 2 4]; % will define polynomial p(x) = x3 + 3x2 + 2x + 4.
>>polyval(p,5) % computes p(5) = 214
Using the plot command, we can draw the curve associated to a
polynomial
plot: example
>>x=0:0.1:5;
>>y=polyval(p,x);
>>plot(x,y,’o’)
MMN - 02 - Intro Matlab
Functions: plot, polynomials, integrals
Matlab also permits data polynomial fitting that is to find the
polynomial which fits the data in least square sense.
polyfit: example
>>x = (0: 0.1: 2.5)’;
>>y = erf(x);
>>p = polyfit(x,y,6) % Here we impose a polynomial degree equal
to 6
>>peval=polyval(p,x);
>>plot(x,y,’o’,x,peval,’-’,’MarkerSize’,10,’LineWidth’,2)
MMN - 02 - Intro Matlab
Functions: plot, polynomials, integrals
MMN - 02 - Intro Matlab
Functions: plot, polynomials, integrals
Exercise 1
Using Matlab command polyfit, build the polynomial regression of
order n = 1, 2, 3 for the set of points which coordinates (x, y) are
given by
x=linspace(0,1.5,6);
y=[0,-0.0630,-0.1440,-0.0810,0.2880,1.1250];
Plot your results.
MMN - 02 - Intro Matlab
Functions: plot, polynomials, integrals
Exercise 1
>>p1=polyfit(x,y,1);
>>p2=polyfit(x,y,2);
>>p3=polyfit(x,y,3);
>>figure
>>plot(x,y,’o k’);
>>hold on;
>>plot(x,polyval(p1,x),’r’);
>>plot(x,polyval(p2,x),’b’);
>>plot(x,polyval(p3,x),’g’);
>>legend(’data’,’order 1’,’order 2’,’order 3’,’Location’,’Best’)
MMN - 02 - Intro Matlab
Functions: plot, polynomials, integrals
MMN - 02 - Intro Matlab
Functions: plot, polynomials, integrals
Exercise 2: spline
Plot the cubic spline interpolating the function 1/(1 + x2 ) at
n = 5, 9, 13 equidistant nodes on the interval [−5, 5] using the
Matlab command spline.
MMN - 02 - Intro Matlab
Functions: plot, polynomials, integrals
Exercise 2: spline
>>x1=linspace(-5,5,5);
>>x2=linspace(-5,5,9);
>>x3=linspace(-5,5,13);
>>f=@(x)1./(1+x.ˆ2);
>>y1=f(x1);y2=f(x2);y3=f(x3);
>>s1=spline(x1,y1);
>>s2=spline(x2,y2);
>>s3=spline(x3,y3);
>>x=linspace(-5,5,100);
>>figure
>>plot(x,f(x),’o’,’MarkerSize’,10);
>>hold on;
>>plot(x,ppval(s1,x),’r’,’LineWidth’,3);
>>plot(x,ppval(s2,x),’b’,’LineWidth’,3);
>>plot(x,ppval(s3,x),’g’,’LineWidth’,3);
>>legend(’exact’,’5 points’,’9 points’,’13 points’,’Location’,’Best’)
MMN - 02 - Intro Matlab
Functions: plot, polynomials, integrals
MMN - 02 - Intro Matlab
Functions: plot, polynomials, integrals
Exercise 3: roots of a polynomial
Using Matlab command roots compute the roots of the following
polynomials
p1 (x) = x3 − 6x2 + 11x − 6 = (x − 1)(x − 2)(x − 3)
p2 (x) = x7 − 7x6 + 21x5 − 35x4 + 35x3 − 21x2 + 7x − 1
= (x − 1)7
MMN - 02 - Intro Matlab
Functions: plot, polynomials, integrals
Exercise 3: roots of a polynomial
Using Matlab command roots compute the roots of the following
polynomials
p1 (x) = x3 − 6x2 + 11x − 6 = (x − 1)(x − 2)(x − 3)
p2 (x) = x7 − 7x6 + 21x5 − 35x4 + 35x3 − 21x2 + 7x − 1
= (x − 1)7
Exercise 3: roots of a polynomial
>>p1=[1,-6,11,-6];
>>roots(p1)
>>p2=[1,-7,21,-35,35,-21,7,-1];
>>roots(p2)
MMN - 02 - Intro Matlab
Functions: plot, polynomials, integrals
Exercise 4: zeros of a function
Given the functions
f (x) = cosh(x) + cos(x) − 4
g(x) = exp(x) − x2
try to find a small interval containing a zero using command f plot.
Compute the zeros of f and g using Matlab command f zero.
MMN - 02 - Intro Matlab
Functions: plot, polynomials, integrals
Exercise 4: zeros of a function
Given the functions
f (x) = cosh(x) + cos(x) − 4
g(x) = exp(x) − x2
try to find a small interval containing a zero using command f plot.
Compute the zeros of f and g using Matlab command f zero.
Exercise 4: zeros of a function
>>fplot(@(x) exp(x)-x.ˆ2,[-1,1]);
>>fzero(@(x) exp(x)-x.ˆ2,-0.6)
>>fplot(@(x) cosh(x)+cos(x)-4,[-3,3]);
>>fzero(@(x) cosh(x)+cos(x)-4,-2)
>>fzero(@(x) cosh(x)+cos(x)-4,2)
MMN - 02 - Intro Matlab
Functions: plot, polynomials, integrals
Exercise 5: integrals
Using Matlab commands quad and quadl compute the integrals
Z 1
I1 = exp(x)dx = e − 1
0
Z 1
I2 = cos(x)dx = sin(1)
0
MMN - 02 - Intro Matlab
Functions: plot, polynomials, integrals
Exercise 5: integrals
Using Matlab commands quad and quadl compute the integrals
Z 1
I1 = exp(x)dx = e − 1
0
Z 1
I2 = cos(x)dx = sin(1)
0
Exercise 5: integrals
>>f=@(x) exp(x);
>>I1=quad(f,0,1) % uses Simpson method
>>g=@(x) cos(x);
>>I2=quadl(g,0,1) % uses high order quadrature
MMN - 02 - Intro Matlab
Defining functions in files
Plan
1 Functions: plot, polynomials, integrals
2 Defining functions in files
3 Differential equations
MMN - 02 - Intro Matlab
Defining functions in files
Defining functions in files
Matlab allows to define a more complex function, lets say ‘myfun’
in a separate file ‘myfun.m’. Here is an example:
Example
Write a file myfun.m for the function
(
t − 3, if t ≤ 4
f (t) =
1, if t > 4
We recall that f is also define by the handle function
>>f=@(t) (t>4).*1+(t<=4).*(t-3);
MMN - 02 - Intro Matlab
Defining functions in files
Defining functions in files
myfun.m (solution 1)
function y=myfun(x)
% x : input variable
% y : output variable
y=ones(size(x));
y(x<=4)=x(x<=4)-3;
MMN - 02 - Intro Matlab
Defining functions in files
Defining functions in files
myfun.m (solution 2)
function y=myfun(x)
% x : input variable
% y : output variable
y=zeros(size(x));
for k = 1:size(x,1)
for l = 1:size(x,2)
if x(k,l) <= 4
y(k,l) = x(k,l)-3;
else
y(k,l) = 1;
end
end
end
MMN - 02 - Intro Matlab
Defining functions in files
Exercise 6: defining functions in a file
Write a function that takes in argument a matrix and returns both:
an integer equal to 1 if the matrix is diagonal dominant, 0 if not ;
the diagonal of the matrix itself. We recall that a matrix A = (aij )
of order n is said to be diagonal dominant if
n
X
|aii | > |aij |
j=1,j6=i
Test your function with the matrices
>>A=diag(3*ones(5,1))+diag(-0.5*ones(4,1),-1)+diag(-
1.5*ones(4,1),1);
>>R=rand(5);
MMN - 02 - Intro Matlab
Defining functions in files
Exercise 6: defining function in a file
function [flag,d]=myfun(A)
% function testing if a matrix is diagonal dominant % A: input
variable (a matrix)
% flag: output (0 if ’no’ or 1 if ’yes’)
flag=1;d=diag(A);% start assuming that A is diagonal dominant
for k=1:size(A,1)
tot=0;
for l=1:size(A,2)
if k∼=l
tot=tot+abs(A(k,l));
end
end
if tot>=abs(A(k,k))
flag=0;break;
end
end
MMN - 02 - Intro Matlab
Defining functions in files
Exercise 6: solution 2
function [flag,d]=myfun2(A)
% function testing if a matrix is diagonal dominant
% A: input variable (a matrix)
% flag: output (0 if ’no’ or 1 if ’yes’)
flag=1;d=diag(A);% start assuming that A is diagonal dominant
for k=1:size(A,1)
tot=sum(abs(A(k,:)))-abs(A(k,k));
if tot>=abs(A(i,i))
flag=0;
break;
end
end
MMN - 02 - Intro Matlab
Defining functions in files
Exercise 6: solution 3
function [flag,d]=myfun3(A)
% function testing if a matrix is diagonal dominant
% A: input variable (a matrix)
% flag: output (0 if ’no’ or 1 if ’yes’)
d=diag(A);% start assuming that A is diagonal dominant
flag=all(2*abs(d)>sum(abs(A),2));
MMN - 02 - Intro Matlab
Defining functions in files
Exercise 6 (bis): Gerschgorin theorem
Given a n × n complex matrix A we define the i − th Gerschgorin
disc Di as
Xn
Di = z ∈ C, |aii − z| ≤ |aij | .
j=1,j6=i
This disc
Pn has center aii in the complex plane and radius
Ri = j=1,j6=i |aij |.
Write a function that checks if an (input) value belongs to a
Gerschgorin disk Di of an (input) matrix for i = 1 . . . n.
MMN - 02 - Intro Matlab
Defining functions in files
Exercise 6 (bis): Gerschgorin.m
function flag=Gerschgorin(A,z)
%A: input matrix
%z: input value (to check)
R=sum(abs(A),2)-abs(diag(A));
%start assuming that z
%does not belong to a Gerschgorin disk
flag=0;
for k=1:size(A,1)
if(abs(z-A(k,k))<=R(k))
flag=1;
break;
end
end
MMN - 02 - Intro Matlab
Differential equations
Plan
1 Functions: plot, polynomials, integrals
2 Defining functions in files
3 Differential equations
MMN - 02 - Intro Matlab
Differential equations
Differential equations
Let I denote an (open) interval on the real line −∞ < t < +∞, and t0 ∈ I.
Let f be a real-valued continuous function on D = I × R. Consider the initial
value problem (
y 0 (t) = f (t, y(t))
y(t0 ) = y0
Theorem
Cauchy-Lipschitz. Suppose that f satisfies the Lipschitz condition i.e. ∃k > 0
such that
|f (t, y1 ) − f (t, y2 )| ≤ k|y1 − y2 |
for every (t, y1 ) and (t, y2 ) in D. Then there exists a unique function y(t) such
that
(i) y(t) ∈ C 1 (I)
(ii) y 0 (t) = f (t, y(t)) for each t ∈ I
(iii) y(t0 ) = y0
MMN - 02 - Intro Matlab
Differential equations
Available solvers in Matlab (for non-stiff systems)
One-step explicit solvers (need only the solution at the immediately
preceding time point yn−1 to compute yn )
ode45: 5th order Runge-Kutta scheme using
Dormand&Prince formula. It should be the first solver to try.
J.R. Dormand; P.J. Prince. A family of embedded Runge-Kutta formulae.
J. Comput. Appl. Mathematics (1980). Vol. 6, p.19–26.
ode23: 3rd order Runge-Kutta scheme using Bogacki&Shampine formula.
P. Bogacki; L.F. Shampine. A 3(2) pair of RungeKutta formulas, Applied
Mathematics Letters. (1989) Vol. 2 (4), p.321–325.
Multi-step explicit solvers (need the solution at several preceding
time points (ym , ..., yn−1 ), m < n − 1, to compute yn )
ode113: variable order Adams-Bashforth-Moulton scheme.
F. Bashforth; J.C. Adams. Theories of Capillary Action. Cambridge
University Press (1883).
MMN - 02 - Intro Matlab
Differential equations
Available solvers in Matlab (for stiff systems)
A differential system is said to be stiff if it presents very large
eigenvalues or condition number. In this case, explicit solvers are
not well suited because they would ask for a very small time step
δt to remain stable.
ode15s: variable order solver based on the backward
differentiation formula (BDF). It is an implicit multistep
solver. Here is an example of 1st BDF scheme
yn+1 = yn + δtf (tn+1 , yn+1 )
MMN - 02 - Intro Matlab
Differential equations
Solving differential equations with Matlab
Consider the following Cauchy problem
(
y 0 (t) = y(t) + sin(t)
(P)
y(0) = 0
The function y(t) = 12 et − sin(t) − cos(t) is an exact solution
of (P). Using Matlab command ode45, compute an approximate
solution of (P) on I = [0, 1] and compare your results with the
exact solution.
file ’myode.m’
function dydt=myode(t,y) % Evaluate ode at time t
dydt=y+sin(t);
MMN - 02 - Intro Matlab
Differential equations
Solving differential equations with Matlab
ode45
>>Tspan=[0 1]; % Solve from t = 0 to t = 1
>>IC=0; % y(t=0)=0
>>[T Y]=ode45(@(t,y) myode(t,y),Tspan,IC); % solve ode using
Runge-Kutta method
>>fplot(@(x) 0.5*(exp(x)-sin(x)-cos(x)),[0,1]);
>>hold on;
>>plot(T,Y,’o r’);
>>legend(’exact’,’ode45’,’Location’,’Best’);
MMN - 02 - Intro Matlab
Differential equations
Solving differential equations with Matlab
MMN - 02 - Intro Matlab
Differential equations
Solving differential equations with Matlab
Exercise 7
We consider the following Cauchy problem
(
y 0 (t) = −20 (y(t) − 1)2
(P)
y(0) = 2
admitting the solution
1
y(t) = 1 +
1 + 20t
Integrate (P) using Matlab commands ode45 and ode15s on
I = [0, 1]. Compare the results. For each method, compute the
number of steps required to solve the differential system (P).
MMN - 02 - Intro Matlab
Differential equations
Solving differential equations with Matlab
Exercise 7: file ’myode.m’
function dydt = myode(t,y)
dydt=-20*(y-1).ˆ2;
Exercise 7: ode45 vs ode15s
>>Tspan=[0,1];
>>IC=2;
>>[T1 Y1]=ode45(@(t,y) myode(t,y),Tspan,IC);
>>[T2 Y2]=ode15s(@(t,y) myode(t,y),Tspan,IC);
>>fplot(@(x) 1+1/(1+20*x),[0,1])
>>hold on;
>>plot(T1,Y1,’r’);
>>plot(T2,Y2,’b’);
>>length(T1) % ≈ 53iterations
>>length(T2) % ≈ 32iterations
MMN - 02 - Intro Matlab
Differential equations
Solving differential equations with Matlab
MMN - 02 - Intro Matlab
Differential equations
Solving differential equations with Matlab
Exercise 8
We consider the second order initial value problem relative to the harmonic
oscillator
2
ẍ + ω x = 0
(P) x(0) = x0
ẋ(0) = v0
q
k
where ω = m . Problem (P) also writes in matricial form
0 d x1 0 1 x1
(P ) = ,
dt x2 −ω 0 x2
where x1 ≡ x (the position) and x2 ≡ ẋ (the velocity).
(i) Using Matlab command ode45, solve (P 0 ) for different initial conditions.
(ii) Repeat the same approach introducing a damping γ = λ/(2m) term in the
oscillator equation ẍ + 2γ ẋ + ω 2 x = 0 for γ 2 > ω 2 , γ 2 < ω 2 and γ 2 = ω 2 .
MMN - 02 - Intro Matlab
Differential equations
Solving differential equations with Matlab
file ’myode.m’
function dxdt = myode(t,x)
w=1;
gamma=0; % we neglect dissipation
dxdt = [x(2); -wˆ2*x(1)-2*gamma*x(2)];
Exercise 8
>>Tspan=[0,20];
>>ICs=[2;0]; % it’s a column vector
>>[t,x] = ode45(@myode,Tspan,ICs);
>>plot(t,x(:,1),’k’);
MMN - 02 - Intro Matlab
Differential equations
References
[1] G. Monegato, Metodi e algoritmi per il calcolo numerico, CLUT
(2008).
[2] E.A. Coddington, N. Levinson, Theory of ordinary differential
equations, McGraw-Hill editions (1972).
[3] V.I. Arnold, Ordinary Differential Equations, Springer (1992).