matlab (math library)

55
MATLAB (Math Library) II Numerical Analysis DWE3214 Prepared by: Dr. Zaid Al-Azzawi

Upload: others

Post on 09-May-2022

10 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: MATLAB (Math Library)

MATLAB

(Math Library)

II

Numerical Analysis

DWE3214

Prepared by: Dr. Zaid Al-Azzawi

Page 2: MATLAB (Math Library)

© Zaid Al-Azzawi 2017 [2]

2.1 Vectors and Matrices:

A row vector [H]= [1 2 3 4 5]; can be entered to MATLAB by:

>>H=[1 2 3 4 5]

H =

1 2 3 4 5

A column vector can be entered to MATLAB by several ways such as:

>>V=[1; 2; 3; 4; 5]

V =

1

2

3

4

5

Or simply:

>> V=[1

2

3

4

5]

V =

1

2

3

4

5

Thus, a matrix [A] of any dimension can be entered using mixed

methods:

A=[10 20 30; 40 50 60; 70 80 90]

Page 3: MATLAB (Math Library)

© Zaid Al-Azzawi 2017 [3]

A =

10 20 30

40 50 60

70 80 90

2.1.1 MATLAB matrix operations:

Table (1): MATLAB basic matrix operations

Operation MATLAB form Mathematical form

Matrix [a11 … a1n; .. … amn] [A]

Addition A+B A+B

Subtraction A-B A-B

Transpose A' AT

Multiply A*B A*B

Multiply by scalar s*A s*aij

Special:

Multiply A.*B aij*bij

Power A.^m aijm

Function F(A) f(aij)

Add scalar A+s aij+s

MATLAB session: __________________________________________

>> format compact

>>C=[-14 4; 1 -18]

C =

-14 4

1 -18

>> Ct=C' % Transpose of [C]

Ct =

-14 1

4 -18

Page 4: MATLAB (Math Library)

© Zaid Al-Azzawi 2017 [4]

>> Ct' % Transpose of C transpose = C

ans =

-14 4

1 -18

>> A=[2 1; 3 0]

A =

2 1

3 0

>> AxB=C*A

AxB =

-16 -14

-52 1

>> CAt=(C*A)' % (C*A) Transpose

CAt =

-16 -52

-14 1

>> A'*C' % (A transpose x C transpose) = (C*A) transpose

ans =

-16 -52

-14 1

>> quit

Page 5: MATLAB (Math Library)

© Zaid Al-Azzawi 2017 [5]

2.1.2 Square and symmetric matrices:

Table (2): MATLAB special matrices

Command Matrix

A=[] empty matrix

diag(A) main diagonal of A

eye(n) (n×n) identity matrix (aij=1)

eye(size(A)) identity matrix [size(I)=size(A)]

ones(m,n) m×n matrix (aij=1)

rand(m,n) m×n matrix of random numbers

zeros(m,n) m×n matrix of zeros

2.1.3 MATLAB matrix functions:

Table (3): MATLAB matrix functions

Operation MATLAB form Mathematical form

Determinant det det(A)

Inverse inv A-1

Rank rank rank(A)

Reduced matrix rref

rrefmovie Ar

Solutions of linear systems:

A is n×n A\b solve Ax=b

A is m×n A\b Solve system with least

squares

MATLAB session: __________________________________________

>> A =[1 3 4; 5 4 7; 0 2 3];

>> b=[1 2 4]';

>> A\b

ans =

-2.2857

-6.1429

5.4286

Page 6: MATLAB (Math Library)

© Zaid Al-Azzawi 2017 [6]

Or we can simply program the desired method of solution

such as:

MATLAB Script: __________________________________________

function [x,det] = gauss(A,b)

% Solves A*x = b by Gauss elimination and computes det(A).

% USAGE: [x,det] = gauss(A,b)

if size(b,2) > 1; b = b'; end % b must be column vector

n = length(b);

for k = 1:n-1 % Elimination phase

for i= k+1:n

if A(i,k) ~= 0

lambda = A(i,k)/A(k,k);

A(i,k+1:n) = A(i,k+1:n) - lambda*A(k,k+1:n);

b(i)= b(i) - lambda*b(k);

end

end

end

for k = n:-1:1 % Back substitution phase

b(k) = (b(k) - A(k,k+1:n)*b(k+1:n))/A(k,k);

end

if nargout == 2; det = prod(diag(A)); end

for k = n:-1:1 % Back substitution phase

b(k) = (b(k) - A(k,k+1:n)*b(k+1:n))/A(k,k);

end

x = b;

MATLAB Script: __________________________________________

function x = gausspiv(A,B)

%The sizes of matrices A,B are supposed to be NA x NA and NA x NB.

%This function solves Ax = B by Gauss elimination algorithm with

pivoting.

NA = size(A,2); [NB1,NB] = size(B);

if NB1 ~= NA, error('A and B must have compatible dimensions'); end

N = NA + NB; AB = [A(1:NA,1:NA) B(1:NA,1:NB)]; % Augmented

matrix

epss = eps*ones(NA,1);

for k = 1:NA

%Scaled Partial Pivoting at AB(k,k) by Eq.(2.2.20)

[akx,kx] = max(abs(AB(k:NA,k))./ ...

Page 7: MATLAB (Math Library)

© Zaid Al-Azzawi 2017 [7]

max(abs([AB(k:NA,k + 1:NA) epss(1:NA - k + 1)]'))');

if akx < eps, error('Singular matrix and No unique solution'); end

mx = k + kx - 1;

if kx > 1 % Row change if necessary

tmp_row = AB(k,k:N);

AB(k,k:N) = AB(mx,k:N);

AB(mx,k:N) = tmp_row;

end

% Gauss forward elimination

AB(k,k + 1:N) = AB(k,k+1:N)/AB(k,k);

AB(k,k) = 1; %make each diagonal element one

for m = k + 1: NA

AB(m,k+1:N) = AB(m,k+1:N) - AB(m,k)*AB(k,k+1:N); %Eq.(2.2.5)

AB(m,k) = 0;

end

end

%backward substitution for a upper-triangular matrix eqation

% having all the diagonal elements equal to one

x(NA,:) = AB(NA,NA+1:N);

for m = NA-1: -1:1

x(m,:) = AB(m,NA + 1:N)-AB(m,m + 1:NA)*x(m + 1:NA,:);

%Eq.(2.2.7)

end

MATLAB Script: __________________________________________

function X = gauseid(A,B,X0,kmax)

%This function finds x = A^-1 B by Gauss–Seidel iteration.

if nargin < 4, tol = 1e-6; kmax = 100;

elseif kmax < 1, tol = max(kmax,1e-16); kmax = 1000;

else tol = 1e-6;

end; if nargin < 4, tol = 1e-6; kmax = 100; end

if nargin < 3, X0 = zeros(size(B)); end

NA = size(A,1); X = X0;

for k = 1: kmax

X(1,:) = (B(1,:)-A(1,2:NA)*X(2:NA,:))/A(1,1);

for m = 2:NA-1

tmp = B(m,:)-A(m,1:m-1)*X(1:m - 1,:)-A(m,m + 1:NA)*X(m + 1:NA,:);

X(m,:) = tmp/A(m,m); %Eq.(2.5.4)

end

X(NA,:) = (B(NA,:)-A(NA,1:NA - 1)*X(1:NA - 1,:))/A(NA,NA);

if nargout == 0, X, end %To see the intermediate results

Page 8: MATLAB (Math Library)

© Zaid Al-Azzawi 2017 [8]

if norm(X - X0)/(norm(X0) + eps)<tol, break; end

X0 = X;

end

MATLAB Script: __________________________________________

function A = LUdec(A)

% LU decomposition of matrix A; returns A = [L\U].

% USAGE: A = LUdec(A)

n = size(A,1);

for k = 1:n-1

for i = k+1:n

if A(i,k) ~= 0.0

lambda = A(i,k)/A(k,k);

A(i,k+1:n) = A(i,k+1:n) - lambda*A(k,k+1:n);

A(i,k) = lambda;

end

end

end

function x = LUsol(A,b)

% Solves L*U*b = x, where A contains both L and U;

% that is, A has the form [L\U].

% USAGE: x = LUsol(A,b)

if size(b,2) > 1; b = b'; end

n = length(b);

for k = 2:n

b(k) = b(k) - A(k,1:k-1)*b(1:k-1);

end

for k = n:-1:1

b(k) = (b(k) - A(k,k+1:n)*b(k+1:n))/A(k,k);

end

x = b;

Page 9: MATLAB (Math Library)

© Zaid Al-Azzawi 2017 [9]

2.2 Eigenvalues and Eigenvectors

Table (4): MATLAB eigenvector functions

Operation MATLAB form Mathematical form

Eigenvalues eig(A) Eigenvalues of (A)

and eigenvectors

[V,D]=eig(A)

Solves for eigenvalues and

eigenvectors of (A)

(V) is a matrix whose columns are

eigenvectors with norm equal to 1.0.

(D) is a diagonal matrix whose

elements are the eigenvalues

(AV=VD).

Characteristic

polynomial Poly Characteristic polynomial for |λI-A|

Roots roots Roots of polynomial p(x)

Symbolic

operations:

Sym.syms Construct symbolic numbers,

variables and objects.

Eig(sym(As)) Eigenvalues and eigenvectors of a

symbolic matrix (As).

Poly(As) Symbolic characteristic polynomial

MATLAB session: __________________________________________

>> A=[ 1 -1 0; 0 1 1; 0 0 -2]

A =

1 -1 0

0 1 1

0 0 -2

>> EIG=eig(A) % determine eigenvalues of A

EIG =

1

1

-2

Page 10: MATLAB (Math Library)

© Zaid Al-Azzawi 2017 [10]

>> POLY=poly(A) % and the characteristic polynomial

POLY =

1 0 -3 2

>> [V,D]=eig(A) % V contains eigenvectors

diag(D) is the eignevalues

V =

1.0000 1.0000 -0.1048

0 0.0000 -0.3145

0 0 0.9435

D =

1 0 0

0 1 0

0 0 -2

>> V3=V(:,3) % take the third column and set V(1,3)=1.0

V3 =

-0.1048

-0.3145

0.9435

>> V33=V3/V(1,3)

V33 =

1.0000

3.0000

-9.0000

>> quit

Page 11: MATLAB (Math Library)

© Zaid Al-Azzawi 2017 [11]

2.3 Polynomials

Polynomial evaluation at any given point:

Suppose P(x)=x2+2x+3 and we want to calculate P(10) ?

>> p=[1 2 3];

>> polyval(p,10)

ans =

123

Roots of polynomial:

Suppose we want to fine the roots of the previous polynomial:

>> roots(p)

ans =

-1.0000 + 1.4142i

-1.0000 - 1.4142i

Page 12: MATLAB (Math Library)

© Zaid Al-Azzawi 2017 [12]

2.4 Approximation of a function

Table (5): MATLAB approximation functions

Operation MATLAB form Result

Polynomial polyfit (x,y,n) Polynomial that fits the data

polyval (p,x) Polynomial evaluation

polyder(p) Derivative of a polynomial

Interpolation interp1(x,y,xi,'method') Interpolate using linear, spline

or cubic functions

Least squares nnls(A,b) Solve Ax=b for x. xi≥0

\ or polyfit Solve Ax=b for an

overdetermined system.

spline spline(x,y,xi) Cubic spline interpolation

MATLAB script ____________________________________________

% interpolate the function y=1/(1+x^2)

% at N+1 points with an Nth degree polynomial,

% then compare with straight-line interpolation,

% Test case is N=10 over the interval x=[-5 5].

N=10; % choose Nth degree polynomial.

x=[-5:1:5]; % 11 points

y=1./(1+x.^2); % runge function

% polynomial fit Nth degree

p=polyfit(x,y,N); % p holds coefficients

xplot=[-5:0.1:5]; % define finer grid (101 points)

f=polyval(p,xplot); % evaluate at points xplot

% straight line interpolation

yst1=interp1(x,y,x,'linear');

% plot

clf

subplot(2,1,1), plot(x,y,'o',xplot,f,'-')

title('Polynomial Interpolation')

axis([-6 6 -0.5 2.5]) % set axis limits

subplot(2,1,2), plot(x,y,'o',x,yst1)

title('Straight Line Interpolation')

axis([-6 6 -0.5 2.5])

%

Page 13: MATLAB (Math Library)

© Zaid Al-Azzawi 2017 [13]

MATLAB script ____________________________________________

% Spline interpolation of the function y=1/(1+x^2) with a cubic polynomial

x=[-5:1:5];

y=1./(1+x.^2);

% spline function

xspline=[-5:0.1:5];

yspline=spline(x,y,xspline);

% plot

clf

plot(x,y,'o',xspline,yspline,'-')

title('Spline Function Interpolation')

axis([-6 6 -0.5 2])

%

MATLAB script ____________________________________________

% least-squares curve fit with a line using \ operator and polyfit.

% the results are displayed and plotted.

x=[0 1 2 3 5]; % define the data points

y=[0 1.4 2.2 3.5 4.4];

A1=[1 1 1 1 1]'; % least square matrix

A=[A1 x'];

Als=A'*A;

bls=A'*y';

% compute least square fit

Xlsq1=Als\bls;

Xlsq2=polyfit(x,y,1);

f1=polyval(Xlsq2,x);

error=y-f1;

disp(' x y f1 y-f1')

table=[x' y' f1' error'];

disp(table)

fprintf('Strike a key for the plot\n')

pause

% plot

clf

plot(x,y,'o',x,f1,'-')

axis([-1 6 -1 6])

title('Least Square Line')

xlabel('X')

ylabel('Y')

% _____________________

Page 14: MATLAB (Math Library)

© Zaid Al-Azzawi 2017 [14]

Results:

x y f1 y-f1

0 0 0.3676 -0.3676

1.0000 1.4000 1.2459 0.1541

2.0000 2.2000 2.1243 0.0757

3.0000 3.5000 3.0027 0.4973

5.0000 4.4000 4.7595 -0.3595

Strike a key for the plot

The following is an interactive program to fit a discrete data:

MATLAB script ____________________________________________

% Example (Polynomial curve fitting)

xData = [-0.04,0.93,1.95,2.90,3.83,5.0,...

5.98,7.05,8.21,9.08,10.09]';

yData = [-8.66,-6.44,-4.36,-3.27,-0.88,0.87,...

3.31,4.63,6.19,7.4,8.85]';

format short e

while 1

k = input('degree of polynomial = ');

if isempty(k) % Loop is terminated

fprintf('Done') % by pressing ’’return’’

break

end

coeff = polynFit(xData,yData,k+1)

sigma = stdDev(coeff,xData,yData)

fprintf('\n')

end

Page 15: MATLAB (Math Library)

© Zaid Al-Azzawi 2017 [15]

OR we can use the MATLAB Basic Fitting tool interactively.

Page 16: MATLAB (Math Library)

© Zaid Al-Azzawi 2017 [16]

2.4.1 MATLAB 2D Interpolation

MATLAB script ____________________________________________

% CLINT2D.M Create data, plot original data and then perform 2D interpolation

%

x=[0:1:4]; % original x points

y=[0:1:4]; % original y points

[X,Y]=meshgrid(x,y) % rows of X are x and columns of Y are y

Z=(X-2).^2+(Y-2).^2; % A matrix Z(x,y)

%

xi=[0:0.2:4]; % x points to interpolate

yi=[0:0.2:4]'; % y points to interpolate

Zi=interp2(X,Y,Z,xi,yi,'cubic');

% plot surface and contour to compare results

clf

subplot(2,1,1), surfc(x,y,Z)

xlabel('Original x')

ylabel('Original y')

title('Surface from z=f(x,y)')

subplot(2,1,2), surfc(xi,yi,Zi)

xlabel('interpolated x')

ylabel('interpolated y')

title('Surface from 2D Interpolation')

%

Page 17: MATLAB (Math Library)

© Zaid Al-Azzawi 2017 [17]

2.5 Numerical Differentiation

The Newton-quotient for a function f(x) is

( )x

xfxxfxxf

−+→=

)(0lim)(

Example: Calculate ?2)( 2 =xatxdx

d

Solution:

Exact solution: = 2x → 2*2=4.0

MATLAB script ____________________________________________

h=1;

x=2;

format long e

for i=1:20

nq=((x+h)^2-(x)^2)/h;

disp([h nq])

h=h/10;

end

Results:

h=1.000000000000000e-008 which gives y'= 3.999999975690115e+000

The diff command:

MATLAB script ____________________________________________

% CLPOLYDV.M Compute derivative of f(x)=2x^4-7x^3+5x^2-1

% Compare diff and polyder results

p=[2 -7 5 0 -1]; % coefficients

pd=polyder(p) % polynomial derivative

xi= linspace(0,3,100);

yder=polyval(pd,xi);

%

Page 18: MATLAB (Math Library)

© Zaid Al-Azzawi 2017 [18]

% Derivative using diff

%

x=[0:0.5:3]; % coarse interval

y=2*x.^4-7*x.^3+5*x.^2-1;

% using diff with 6 points

dely= diff(y)./diff(x);

xd=x(1:length(x)-1)

%

% more accurate diff using 100 points

yder99=2*xi.^4-7*xi.^3+5*xi.^2-1;

dely1= diff(yder99)./diff(xi);

xd1=xi(1:length(xi)-1);

%

clf

plot (xi,yder,'-'), hold on % polyder

plot (xd1,dely1,'-.') % diff 99 points

plot (xd,dely,'o') % diff 6 points

title('Derivative Approximation')

xlabel('X'), ylabel('Dy')

legend('polyder','diff 99pts','diff 6pts')

hold off

% --------------------------------------------------------------

Results:

pd =

8 -21 10 0

xd =

0 0.5000 1.0000 1.5000 2.0000 2.5000

Page 19: MATLAB (Math Library)

© Zaid Al-Azzawi 2017 [19]

2.6 Taylor Series

The command taylor expand the function using Taylor series

MATLAB script ____________________________________________

>> f2='exp(x)';

>> T2=taylor(sym(f2))

Example: Two dimensional Taylor series

Expanding about the origin, the series would be

...)()(),( 2

2,21,2

2

0,21,10,10,0 ++++++= ycxycxcycxccyxF

Assuming that the function can be differentiated at the origin, the first six

coefficients of the 2D Taylor series expansion become

.)0,0(

!2

1,.

)0,0(

!2

2,.

)0,0(

!2

1

,)0,0(

,.)0,0(

,)0,0(

2,22

2

1,2

2

0,22

2

1,10,10,0

cy

Fc

yx

Fc

x

F

cy

Fc

x

FcF

=

=

=

=

=

=

The function 221),( yxyxf ++= can be expanded in a 2D Taylor

series about the point (0,0) using the coefficient from the above equation.

Computing the terms up to the second derivative in x and y leads to the

results:

.1)0,0(,1)0,0(

,0)0,0(

,0)0,0(,0)0,0(

,1)0,0(

2,20,2

1,2

1,10,1

0,0

====

==

====

==

cfcf

cf

cfcf

cf

yyxx

xy

yx

( )22

2

11),( yxyxf ++

Page 20: MATLAB (Math Library)

© Zaid Al-Azzawi 2017 [20]

The accompanying MATLAB script calculates and plots the values for

221),( yxyxfz ++==

and the Taylor series approximation for a fixed value of y as input. The

Figure below shows the results for y = 0. Here we determined the shape

of the graph by the method of sections. The section of f(x,y) shown is in

the vertical xz-plane defined by y = 0.

MATLAB script ____________________________________________

% plots Taylor series approximation and function f(x,y)=sqrt(1+x^2+y^2)

% input y value.

clear

clf

x=[-2:0.2:2];

y=input('Input y value= ')

z1=x.^2+y.^2; % quadratic term

Z=sqrt(1+z1); % function

ztay=1+z1/2; % Taylor approximation

% plot

plot(x,ztay,'-')

hold % plot on same axis

plot(x,Z,'--')

legend('f(x,y)','Taylor approximation')

title(['Approximation of z=sqrt(1+x^2+y^2), ', 'y= ', num2str(y)])

xlabel('X')

ylabel('Z')

zoom % change resolution with mouse

Page 21: MATLAB (Math Library)

© Zaid Al-Azzawi 2017 [21]

2.7 Numerical Integration

Table (6): MATLAB commands for integration

Command Purpose

trapz Trapezoidal numerical integration

quad Simpson's rule integration

quad8 Newton-Cotes integration

int Symbolic integration

MATLAB session ___________________________________________

>> % use the command int to integrate y=x^2 symbolically

>> syms x % define the independent variable

>> y=x^2 % define the function y=f(x)

>> int (y) % integrate the function

ans=

1/3 x3

********************************

>> syms x

>> int(sin(x))

ans=

-cos(x)

********************************

>> syms x

>> y=x^2

>> int (y,0,10) % integrate the function from x=0 to x=10

ans=

1000/3

*********************************

>> y=inline('x.^2');

>> Q=quad(y,0,10)

ans=

3.33 e002

*********************************

Page 22: MATLAB (Math Library)

© Zaid Al-Azzawi 2017 [22]

We can program Trapezoid rule in two different ways:

MATLAB script ____________________________________________

% Integration of y=x2: method 1.

a=0;b=10;h=1; % h=1 coarse interval. a,b integration limit

x=a+h:h:b-h;

y=sum(x.^2);

y=h/2*((a^2)+(b^2)+(2*y));

disp('y='); disp(y)

**********************************************************

>> % Integration of y=x2: method 2. Using the function trap.M

>> trap (x,0,10,0.1)

% the function trap.M must be saved before executing the last sentence.

function [Q]=trap(x,a,b,h)

x=a+h:h:b-h;

Q=h/2*(a^2+(2*sum(x.^2))+b^2)

***********************************************************

MATLAB Symbolic 2D Integration

Consider evaluating the integral

( ) +=

0

2

cossin)],([ dxdyxyyxyxfI

This double integral is easily evaluated analytically, with the result

8696.92 −=−= I

The accompanying MATLAB script shows the use of int to integrate this

2D function. First, int is called to evaluate the inner integral with respect

to y, leaving x as symbolic variable. Then, the outer integral is evaluated

using the x limits. The results from the M.file (edited) are included

following the script.

Page 23: MATLAB (Math Library)

© Zaid Al-Azzawi 2017 [23]

MATLAB script ____________________________________________

% perform 2D symbolic integration of the function

% x*sin(y)+y*cos(x) over fixed limits pi < y < 2pi , 0 < x< pi

inty=int(' x*sin(y)+y*cos(x)','y',pi,2*pi) % inner integral

intx=int(inty,'x',0,pi) % outer integral

twodint=numeric(intx) % convert to a number

% *********************************************************

% Results

inty =

-2*x+3/2*pi^2*cos(x)

intx =

-pi^2

twodint =

-9.8696

***********************************************************

Page 24: MATLAB (Math Library)

© Zaid Al-Azzawi 2017 [24]

2.8 Numerical Solution of Differential Equations

The numerical solution to the differential equation ( )xtfdt

tdx,

)(=

is a sequence of vectors nxxx ˆ.....,ˆ,ˆ21 corresponding to an increasing

sequence of time points nttt .....,, 21 such that ( )itx̂ approximates ( )itx .

2.8.1 First Order Differential Equations 2.8.1.1 First order Euler's method:

MATLAB script ____________________________________________

% Euler method to solve the bacteria growth in a colony for dN/dt=r*N

h=0.1; % time step= 0.5 hr

r=0.8; % rate of growth

a=0; % initial t=0

b=10; % required t=10 hrs

m=(b-a)/h;

N=zeros(1,m+1);

N(1)=1000;

t=a:h:b;

for i=1:m

N(i+1)=N(i)+r*h*N(i);

end

% Exact solution

Nex=N(1)*exp(r*t);

format bank

disp([t' N' Nex'])

plot(t,N),xlabel('Hours'), ylabel('Bacteria')

hold on

plot(t,Nex,'--r')

legend ('Eulers','Exact')

Page 25: MATLAB (Math Library)

© Zaid Al-Azzawi 2017 [25]

2.8.1.2 Predictor-Corrector method

MATLAB script ____________________________________________

% Predictor-Corrector method

h=0.5; % time step= 0.5 hr

r=0.8; % rate of growth

a=0; % initial t=0

b=10; % required t=10 hrs

m=(b-a)/h;

Np=zeros(1,m+1);

Nc=zeros(1,m+1);

Np(1)=1000;

t=a:h:b;

for i=1:m

Np(i+1)=Np(i)+h*r*Np(i);

Nc(i+1)=Np(i)+(h/2)*((r*Np(i))+(r*Np(i+1)));

end

% Exact solution

Nex=Np(1)*exp(r*t);

format bank

disp([t' Np' Nc' Nex'])

plot(t,Nc),xlabel('Hours'), ylabel('Bacteria')

hold on

plot(t,Nex,'--r')

legend ('Eulers','Exact')

Note: 4th order Runge-Kutta method will be programmed later in

second order D.E's for the pendulum problem.

Page 26: MATLAB (Math Library)

© Zaid Al-Azzawi 2017 [26]

When the MATLAB commands are used to solve the

equations numerically, the time points will be chosen automatically by

the routine, and the user has no direct control over their selection. The

automatic selection of the time points is made by the program to achieve

the specified accuracy.

MATLAB differential-solving routines ode23 and ode45 do not require

time invariance or even linearity.

When using ode23 and ode45, the system of equations must be defined in

a separate function M.file. A typical call to ode23 is:

[t,x] = ode23 ('cl2ordf', [t0 tf], x0, OPTIONS, p1, p2, ...)

The required parameters for the command are the name of the function

M.file defining the equation (cl2ordf), the initial time (t0), the final time

(tf), and the vector (x0) defining the initial conditions at the initial time.

There are various options, indicated by the argument OPTIONS,

including one called tolerance, which defines the desired accuracy of the

solution, (default 1*10-3).

MATLAB Linear D.E's example

MATLAB script ____________________________________________

>> % the following scripts solves the D.E dy/dt=y*(1-t) using MATLAB

>> % routines.

>> % the M.file func1.m define the D.E

>> y0=1; tspan=[0 5];

>> [tt,yy]=ode45('func1',tspan,y0)

MATLAB script ____________________________________________

% Defining the D.E

function [value]=func1(t,y)

value=y*(1-t);

% end

Page 27: MATLAB (Math Library)

© Zaid Al-Azzawi 2017 [27]

2.8.2 MATLAB Linear system example

A system of D.E's in the form:

( ),)( tAxtx =

where A is a matrix of constants is a special case. This yields a linear

relationship between x and x in the form of :

( )( )

( )

( )( )

( )

=

tx

tx

tx

aaa

aaa

aaa

tx

tx

tx

nnnnn

n

n

n

2

1

21

22221

11211

2

1

Example: Solve the following system of linear D.E's?

)()(4)(

)()()(

tytxty

tytxtx

+=

+=

The accompanying M.file CL2ORD.M solves the equation set and plot

the results.

The function CL2ORDF.M defines the system of first order D.E's.

MATLAB script ____________________________________________

% CL2ORD.M- Plot solution to D.E system xdot=Ax:

% this M.file uses function CL2ORDF.M to define equations and ode23 to solve.

% INPUT: final time, plot is from t=0 to t=tfinal

% (system matrix is defined as A=[1 1; 4 1]; x(0)=[1 1]

% OUTPUT: A plot of solutions x1 and x2 versus t.

A=[1 1; 4 1];

t0=0;

tf=input('input tfinal- function is exp(-t)+exp(3t)= ')

% Input values x1(0)=1, x2(0)=1. (defined as a column vector).

x0=[1 1]';

Page 28: MATLAB (Math Library)

© Zaid Al-Azzawi 2017 [28]

tspan=[t0 tf];

[t,x]=ode23('cl2ordf',tspan,x0,[],A); % MATLAB Runge-Kutta routine

plot(t, x(:,1), '+', t, x(:,2), '-')

title('Solution of dx/dt = Ax')

xlabel('Time'); ylabel('x1 and x2')

legend('x1', 'x2')

% end

MATLAB script ____________________________________________

% Function CL2ORDF.M

function x_prime=cl2ordf(t,x,flag,A) % flag is a dummy command

x_prime=A*x;

Another example is the predator-prey model (Chaos):

Example:

120

3.08.0;6.02.1

===

+−=−=

yxtat

xyydt

dyxyx

dt

dx

Page 29: MATLAB (Math Library)

© Zaid Al-Azzawi 2017 [29]

MATLAB script ____________________________________________

>> % solve the above system of equations where x=y(1) and y=y(2)

>> % using the M.file called predprey

>> tspan=[0,20];

>> y0=[2,1];

>> [t,y]=ode23('predprey',tspan,y0);

>> plot(t,y)

MATLAB script ____________________________________________

% Function PREDPREY

function yp=predprey(t,y)

yp=[1.2*y(1)-0.6*y(1)*y(2); -0.8*y(2)+0.3*y(1)*y(2)];

Note: in addition it is also instructive to generate a state-space plot; that

is; a plot of the dependent variables versus each other by:

>> plot (y(:,1), y(:,2))

Page 30: MATLAB (Math Library)

© Zaid Al-Azzawi 2017 [30]

2.8.3 Second Order Differential Equations

Example: Swinging pendulum

The governing D.E is

2

2

2

sec/2.3220sin ftgftll

g

dt

d===+

This second order D.E can be reduced to a couple of first order D.E as

follows:

0.0)0(sin

4/)0(

=−=

==

vl

g

dt

dv

pivdt

d

And this can be solved using MATLAB solving routines:

Note: let vyy == )2()1(

MATLAB script ____________________________________________

>> % the following M.file calls the function pend.m which defines the D.Es

>> tspan=[0,1.6];

>> y0=[pi/4,0.0];

>> [t,y]=ode23('pend', tspan, y0);

>> plot (t,y)

MATLAB script ____________________________________________

% Function PEND.M

function yp=pend(t,y)

yp=[y(2);(-32.2/2)*sin(y(1))];

************************

Page 31: MATLAB (Math Library)

© Zaid Al-Azzawi 2017 [31]

Or we can program it as follows:

Runge-Kutta 4th order method

MATLAB script ____________________________________________

% Runge-Kutta method to solve the second order pendulum problem

% after reducing it to 2 first order D.E's

h=0.05; % time step= 0.05 sec

a=0; % initial t=0

b=1.6; % required t=1.6 sec

m=(b-a)/h;

theta=zeros(1,m+1);

V=zeros(1,m+1);

theta(1)=0.785398;

V(1)=0.0;

t=a:h:b;

for i=1:m

dtheta1=h*(V(i));

dV1=h*((-32.2/2)*sin(theta(i)));

dtheta2=h*(V(i)+(dV1/2));

dV2=h*((-32.2/2)*sin(theta(i)+(dtheta1/2)));

dtheta3=h*(V(i)+(dV2/2));

dV3=h*((-32.2/2)*sin(theta(i)+(dtheta2/2)));

dtheta4=h*(V(i)+dV3);

dV4=h*((-32.2/2)*sin(theta(i)+dtheta3));

theta(i+1)=theta(i)+(1/6)*(dtheta1+(2*dtheta2)+(2*dtheta3)+dtheta4);

V(i+1)=V(i)+(1/6)*(dV1+(2*dV2)+(2*dV3)+dV4);

end

format bank

disp([t' theta' V' ])

Another programming method gives the program a more generalized

solution:

MATLAB script ____________________________________________

% the clrk4 routine is written to any first-order differential equation

% the MATLAB command feval is uses to evaluate the function that

% is passed to the clrk4 routine. The call to clrkr4 would be

% [T,Y]=clrk4('function', a, b, m, y0), where 'function' is the name of

Page 32: MATLAB (Math Library)

© Zaid Al-Azzawi 2017 [32]

% the MATLAB function file (FUNCTION.M) that defines the input

% function to the differential equation (clrk4exf.M).

function [T,Y]=clrk4(f,a,b,m,y0)

% Call: [T,Y]=clrk4(f,a,b,m,y0) solves Ydot=f(T,Y) on t=[a,b].

% Inputs: f M.file defining input function; interval a,b; m points in

% interval; y0 initail value.

% Outputs: T, Y solution by 4th order Runge-Kutta method

h=(b-a)/(m-1); % step size

T=zeros(m,1); % column vector of time points

Y=zeros(m,1); % column vector of solution points

T(1)=a;

Y(1)=y0;

for I=1:m-1; % there are m-1 steps and m points

tI=T(I); % - step through m-1 intervals

yI=Y(I); %

k1=h*feval(f,tI,yI); % Runge-Kutta coefficients

k2= h*feval(f,tI+h/2,yI+k1/2);

k3= h*feval(f,tI+h/2,yI+k2/2);

k4= h*feval(f,tI+h,yI+k3);

Y(I+1)=yI+(k1+2*k2+2*k3+k4)/6;

T(I+1)=a+h*I; % next time step

end

MATLAB script ____________________________________________

% Function clrk4exf(t,y)

function ydot= clrk4exf(t,y)

% call: Ydot= clrk4exf(t,y) define ydot=f(t,y) for each t

ydot=y; % define first order system

To call the routine clrk4.M which in turn will call the function

clrk4exf.M use the following command:

[trk4,yrk4]=clrk4('clrk4exf',a,b,m,y0)

Page 33: MATLAB (Math Library)

© Zaid Al-Azzawi 2017 [33]

The following routine clrk4ex.m is meant to compare between the

solution of clrk4 routine and the ode45 built in routine:

MATLAB script ____________________________________________

% CLRK4DX.M Runge-Kutta solution of ydot=f(t,y); t=[a,b] to

% compare clrk4 and ode45 solutions.

% Inputs: a,b interval endpoints; m points; y0 initial value

% Calls function clfrk4exf to define f(t,y)

a=input('Input starting point a = ') % a=0

b=input('Input end point b = ') % b=1

m=input('Number of points m = ') % m=8

y0=input('Initial value y0 =') % y0=1

% Solve with fixed step size

[Trk4,Yrk4]=clrk4('clrk4exf',a,b,m,y0); % clrk4 solution

% ode45 solution

[Tode45,Yode45]=ode45('clrk4exf', [a,b] ,y0); % ode45 solution

%

% Compare solution with clrk4 and ode45

Yexrk4=exp(Trk4);

Yexode=exp(Tode45);

erk4=abs(Yrk4-Yexrk4);

eode45=abs(Yode45-Yexode);

clf

figure(1), plot(Trk4, Yexrk4, '+', Trk4, Yrk4,'x')

hold on

plot(Tode45, Yode45)

fprintf('Strike a key to continue')

pause

hold off

% Compare error

figure(2), semilogy(Trk4, erk4, '--', Tode45, eode45, '-')

xlabel('Time in seconds')

ylabel('log10 Error')

title('Errors comparing CLRK4 (- - -) and ODE45 (solid line)')

grid

Page 34: MATLAB (Math Library)

© Zaid Al-Azzawi 2017 [34]

2.8.4 MATLAB Solution of Coupled Second Order Equations:

The equations of the motion for the coupled mass system are:

)()()()(

,)()()()(

2312222

1221111

tyktytyktym

tytyktyktym

−−−=

−+−=

The coupled equation can be written as a first-order system by defining

)()(

,)()(

,)()(

,)()(

24

13

22

11

tytx

tytx

tytx

tytx

=

=

=

=

and substituting the new variables in the original equation. The result is

)()()()(

,)()()()(

)()()(

)()()(

2

2

321

1

224

2

1

21

1

2113

422

311

txm

kktx

m

ktytx

txm

ktx

m

kktytx

txtytx

txtytx

+−==

+

+−==

==

==

The results for the special case of mmmandkkkk ===== 21321

becomes:

1 2

1 2 3

Page 35: MATLAB (Math Library)

© Zaid Al-Azzawi 2017 [35]

)(2

)()(

,)()(2

)(

)()(

)()(

214

213

42

31

txm

ktx

m

ktx

txm

ktx

m

ktx

txtx

txtx

−=

+−=

=

=

Thus, the form of the last equation is Axx = , where

−=

002

002

1000

0100

m

k

m

km

k

m

kA

Analysis. Letting k=1 and m=1 for simplicity, the eigenvalues of the

system matrix were found using MATLAB command eig to be ±1.0i and

±√3.0i. The fundamental, or natural, frequencies of oscillation are w1=1

and w2=√3.0 rad/sec. examining the eigenvectors (not shown) indicates

that are two modes of oscillation. The eigenvectors associated with the

natural frequencies are called the normal modes of the system. They

describe the relative amplitudes of the displacement of the masses if the

system vibrated only at the corresponding natural frequency. However,

the absolute amplitudes depends on the initial conditions.

MATLAB Script ____________________________________________

% Example.M use MATLAB ode23 to solve the system

% y1''=-2y1+y2

% y2''=y1-2y2

% transformed into the system xdot=Ax where A is 4x4

% INPUTS: Initial time, final time, initial conditions and title

% OUTPUTS: A (global variable); plot the motion y1(t), y2(t)

% Pass A to function CLDESF

A=[0 0 1 0; 0 0 0 1; -2 1 0 0; 1 -2 0 0] % system matrix

t0=input('Initial time = ')

tf=input('Final time = ')

x0=input('[y1(t0) y2(t0) doty1(t0) doty2(t0)] = ')

x0t=x0; % transpose of initial cond. for ode23

Page 36: MATLAB (Math Library)

© Zaid Al-Azzawi 2017 [36]

% Call function cldesf to define state equations.

[t,x]=ode23('cldesf', [t0, tf],x0t, [],A); % numerical sol. of sys. y values

y1=x(:,1); % changes to physical variable

y2=x(:,2);

% plot y1 and y2, the motion of the masses

titlef= input ('Title = ', 's') % input the title

subplot(2,1,1) , plot(t,y1) % plot 2 graphs on the axis

ylabel('Displacement y1')

subplot(2,1,2) , plot(t,y2)

ylabel('Displacement y2')

xlabel('Time')

title(eval('titlef'))

the function cldesf defines the equation set

MATLAB Script ____________________________________________

% Example.M

function xdot=cldesf(t, x, flag, A)

xdot=A*x;

Page 37: MATLAB (Math Library)

© Zaid Al-Azzawi 2017 [37]

MATLAB input and output for the first case:

A =

0 0 1 0

0 0 0 1

-2 1 0 0

1 -2 0 0

Initial time = 0

t0 =

0

Final time = 20

tf =

20

[y1(t0) y2(t0) doty1(t0) doty2(t0)] = [1, 1,0,0]

x0 =

1 -1 0 0

Title = In-Phase Motion

titlef =

In-Phase Motion

MATLAB input and output for the second case:

A =

0 0 1 0

0 0 0 1

-2 1 0 0

1 -2 0 0

Initial time = 0

t0 =

0

Final time = 20

tf =

20

[y1(t0) y2(t0) doty1(t0) doty2(t0)] = [1,-1,0,0]

x0 =

1 -1 0 0

Title = Out-of-Phase Motion

titlef =

Out-of-Phase Motion

Page 38: MATLAB (Math Library)

© Zaid Al-Azzawi 2017 [38]

2.8.5 Stiff Differential Equations

A stable differential equation is called stiff when it has a decaying

exponential particular solution with a time constant which is very small

relative to the interval over which it is being solved. For higher-order

differential equations with several solutions, if the solutions decay at rates

that differ by a great deal, the equations are called stiff also.

To solve stiff differential equations, MATLAB has routines specifically

designed to overcome the numerical problems involved.

Table (7): MATLAB commands for differential equations

Command Action

ode45 Solves nonstiff differential equations, medium-order method

ode23 Solves nonstiff differential equations, low-order method

ode113 Solves nonstiff differential equations, variable-order method

ode15s Solves stiff differential equations, variable-order method

ose23s Solves stiff differential equations, low-order method

ode23tb Solves stiff differential equations, low-order method

Example: The stiff differential equation

0)0(,1)0(,09999.0)(100)( ===++ xxxtxtx

has the closed form solution

tt eetx 01.099.99 0001.10001.0)( −− +−=

>> % using dsolve command will lead to the following answer

>> yeq1= 'D2x+100 * Dx+0.9999*x =0';

>> y1=dsolve (yeq1, 'x(0)=1', 'Dx(0)=0', 't')

>> ezplot(y1)

Results:

y1 =

9999/9998*exp(-1/100*t)-1/9998*exp(-9999/100*t)

Which is the same as above.

Page 39: MATLAB (Math Library)

© Zaid Al-Azzawi 2017 [39]

>> % solution using ode15s

>> % the following M.file calls the function stiff.m which defines the D.Es

>> tspan=[-6,1];

>> y0=[1,0];

>> [t,y]=ode15s('stiff', tspan, y0);

>> plot (t,y(1))

% Function Stiff.M

function yp=stiff(t,y)

yp=[y(2);-100*y(2)-0.9999*y(1)];

Page 40: MATLAB (Math Library)

© Zaid Al-Azzawi 2017 [40]

2.8.6 Partial Differential Equations

2.8.6.1 Laplace's equation in a rectangle (Dirichlet problem):

( ) ( )0

,,2

2

2

2

=

+

y

yx

x

yx

Using separation of variable, the final

result will be as follows:

( )

=Oddm

a

bmm

a

ym

a

xm

Vyx

sinh

sinhsin4

, 0

MATLAB Solution: Although MATLAB does not have built-in functions

that solve partial differential equations, MATLAB programs can be

written to solve the equations numerically or to plot solutions derived

analytically. Fourier coefficients can be computed with MATLAB

commands, as will be shown.

The professional version of MATLAB can be extended by the addition of

a Partial Differential Equation Toolbox, available from The MathWorks.

Applications areas for the Toolbox include structural mechanics,

electromagnetic, and heat transfer.

Example: MATLAB plot of Laplace Equation Solution

MATLAB can be use to help us visualize the solution to Laplace's

equation for the problem presented above. The accompanying script uses

Symbolic Math Toolbox commands to compute the Fourier series

coefficients.

As a specific case, let φ(x,b)=100 at the top boundary of the rectangle.

Then the numerical solution is computed for the first 10 terms of the

potential. (If a greater number of terms is taken in the series, the potential

Φ=0

Φ=0 Φ=0

Φ=Vo

x

y

a 0

b

Page 41: MATLAB (Math Library)

© Zaid Al-Azzawi 2017 [41]

will appear smoother near the boundary, but some overshoot is always

present).

MATLAB Script ____________________________________________

% Example solve Laplace's equation in 2D with the conditions

% bx1=f(0,y)=0; bx2=f(a,y)=0;by1=f(x,0)=0; by2=f(x,b)=100

% The dimensions are a=16 and b=9

clear % clears variables and

clf % figures

%

a=16; % dimensions of the region

b=9;

V0=100; % constant potential at y=b (top)

%

% Solve for Fourier coefficients- symbolic solution

%

Nmax=19; % compute 1, ….. , Nmax terms

sinhb='sinh(m*pi*b/a)';

for m=1:1:Nmax;

fn='V0*sin(m*pi*x/a)';

intx=int(fn,'x',0,'a'); % symbolic integral

am=symdiv(intx,'a/2'); % symbolic division

am=symdiv(am,sinhb);

am=eval(am);

A(m)=numeric(am); % convert to numbers

end

%

% Plot the results

%

dx=0.5; % increment

dy=0.5;

[x,y]=meshgrid(0:dx:a,0:dy:b);

fxy=zeros(size(x));

for m=1:2:Nmax; % odd components 1,3,5, … , Nmax

fxy=fxy+A(m)*sin(m*pi*x/a).*sinh(m*pi*y/a);

end

surf(x,y,fxy) % 3D view

axis([0 16 0 9 0 120]) % set axis

title('Solution of the Laplace 2D equation')

pause

%

Page 42: MATLAB (Math Library)

© Zaid Al-Azzawi 2017 [42]

% Contour view

%

figure(2) % new figure

[Dx,Dy]=gradient (fxy,dx,dy);

v=0:10:100; % define equipotentials

c=contour(x,y,fxy,v);

vc=[10 50 90]; % label a few equipotentials

clabel(c,vc);

hold on

xlabel('X')

ylabel('Y');

title('Potential')

grid

Page 43: MATLAB (Math Library)

© Zaid Al-Azzawi 2017 [43]

2.8.6.2 Parabolic equation in a rectangle (Crank-Nicolson implicit

method):

( ) ( )

2

,1,,11,11,1,1

2

1,11,1,1

2

,1,,1

2

2

,1,

2

2

/

2222

22

2

1

1,

hkrwhere

rUUrrUrUUrrU

h

UUU

h

UUU

x

u

jandjofaveragethetakingk

UU

t

u

x

u

t

u

jijijijijiji

jijijijijiji

ththjiji

=

+−+=−++−

+−+

+−=

+−

=

=

+−++++−

+−+++−+

+

Example: Let

0.101.01.0

12/1)1(2

2/102),(

0),1(),0(

===

=

==

rkh

xx

xxoxU

tUtU

jijijijiji UUUUU,1,11,11,1,1 4

+−++++− +=−+−

...2,

1,

1

0

i

i

Ufindjfor

Ufindjfor

=

=

Note: Unlike the explicit method, in this method for each jth row there

will be a new matrix to be solved to find the unknowns.

Page 44: MATLAB (Math Library)

© Zaid Al-Azzawi 2017 [44]

Taking j=0 for example:

8.08.004

0.16.04

8.04.04

6.02.04

4.0040

54

543

432

321

2

+=−+−

+=−+−

+=−+−

+=−+−

+=−+

UU

UUU

UUU

UUU

UUl

=

−−

−−

−−

6.1

6.1

2.1

8.0

4.0

42000

14100

01410

00141

00014

5

4

3

2

1

U

U

U

U

U

:where

gAv =

=

−−−

nn

nnn

ba

cba

cba

cba

cb

A

111

333

222

11

.........

Note: the step length k=0.01 and h=1/(2×n), is chosen because of

symmetry.

Page 45: MATLAB (Math Library)

© Zaid Al-Azzawi 2017 [45]

MATLAB Script ____________________________________________

% parabolic equation example

format compact

n=5;

k=0.01;

h=1/(2*n);

r=k/h^2;

% set up the (sparse) matrix [A]

b=sparse(1:n, 1:n, 2+2*r, n, n); % b(1) .. b(n)

c=sparse(1:n-1, 2:n, -r, n, n); % c(1) .. c(n-1)

a=sparse(2:n, 1:n-1, -r, n, n); % a(2) .. a(n)

A=a+b+c;

A(n,n-1)=-2*r; % symmetry: a(n)

full(A)

disp('')

u0=0; % BC's

u=2*h:2*h:2*h*n; % IC's

u(n+1)=u(n-1); % symmetry

disp([0 u(1:n)])

for t=k:k:10*k

g=r*([u0 u(1:n-1)]+ u(2:n+1))+ (2-2*r)*u(1:n); % Right hand side of the equation

v=A\g';

disp([t v'])

u(1:n)=v;

u(n+1)=u(n-1);

plot(t,v'); hold on

end

xlabel('Time')

ylabel('X')

Page 46: MATLAB (Math Library)

© Zaid Al-Azzawi 2017 [46]

2.8.6.3 Hyperbolic Equations

The vibrating string

Page 47: MATLAB (Math Library)

© Zaid Al-Azzawi 2017 [47]

Page 48: MATLAB (Math Library)

© Zaid Al-Azzawi 2017 [48]

Page 49: MATLAB (Math Library)

© Zaid Al-Azzawi 2017 [49]

Page 50: MATLAB (Math Library)

© Zaid Al-Azzawi 2017 [50]

Page 51: MATLAB (Math Library)

© Zaid Al-Azzawi 2017 [51]

String vibration program

Page 52: MATLAB (Math Library)

© Zaid Al-Azzawi 2017 [52]

Page 53: MATLAB (Math Library)

© Zaid Al-Azzawi 2017 [53]

Page 54: MATLAB (Math Library)

© Zaid Al-Azzawi 2017 [54]

Page 55: MATLAB (Math Library)

© Zaid Al-Azzawi 2017 [55]