Matlab
Matlab
TO MATLAB PROGRAMMING
Lec 1.1: MATLAB Basics
Dr. Niket Kaisare
Department of Chemical Engineering
IIT–Madras
Indian captain, Mahendra Singh Dhoni, hits a ball with initial velocity of 35
m/s and angle of 45○. If the boundary is at a distance of 75 m, will he score
a six?
• Setting up the problem:
• !"#$ = 35; *+ = !"#$ cos //4 ; !+ = !"#$ sin //4
• 4 5 = *; 6 5 = !
• * 5 = −8*; ! 5 = −9;
Result
MATLAB Code
%% Define Parameters and Initial Conditions
param.g = 9.81; % gravitational acceleration
param.kappa = 0.006; % air drag coefficient
u0 = 35*cos(pi/4);
v0 = 35*sin(pi/4);
%% Animating results
exitCode = ballAnimation(tOut,XOut);
MATLAB Code: Main Code Blocks
%% Define Parameters and Initial Conditions
Output block
figure(1);
plot(XOut(:,1),XOut(:,2),'bo');
xlabel('x (m)'); ylabel('y (m)');
%% Animating results
exitCode = ballAnimation(tOut,XOut);
MATLAB Code: Key Parts
%% Define Parameters and Initial Conditions
param.g = 9.81; Comment
u0 = 35*cos(pi/
Assignment
(Math) Expression
Calling a function
plot(XOu
Calling a function
MATLAB Code
%% Define Parameters and Initial Conditions
param.g = 9.81; % gravitational acceleration
param.kappa = 0.006; % air drag coefficient
u0 = 35*cos(pi/4);
v0 = 35*sin(pi/4);
%% Animating results
exitCode = ballAnimation(tOut,XOut);
Basic Data Types
• Assigning variables
• Arrays / Matrices
• Suppress “echo”
• MATLAB basics
• Arrays: Unlocking potential of MATLAB
• Loops and Execution Control
• MATLAB files: Scripts and Functions
• Program Output and Plotting
1
12/17/15
Indian captain, Mahendra Singh Dhoni, hits a ball with initial velocity of 35
m/s and angle of 45○. If the boundary is at a distance of 75 m, will he score
a six?
• Setting up the problem:
2
12/17/15
Result
MATLAB Code
%% Define Parameters and Initial Conditions
param.g = 9.81; % gravitational acceleration
param.kappa = 0.006; % air drag coefficient
u0 = 35*cos(pi/4);
v0 = 35*sin(pi/4);
%% Animating results
exitCode = ballAnimation(tOut,XOut);
3
12/17/15
Input block
param.g = 9.81; % gravitational acceleration
param.kappa = 0.006; % air drag coefficient
u0 = 35*cos(pi/4);
v0 = 35*sin(pi/4);
Computation
%% Setting up and Solving the problem
X0 = [0; 0; % starting position is the origin
u0; v0]; % starting velocity is given
tSpan = [0 20]; % simulation time
[tOut, XOut] = ode45(@ballTrajectoryFun,tSpan,X0, [], param);
Output block
figure(1);
plot(XOut(:,1),XOut(:,2),'bo');
xlabel('x (m)'); ylabel('y (m)');
%% Animating results
exitCode = ballAnimation(tOut,XOut);
(Math) Expression
Calling a function
plot(XOu
Calling a function
4
12/17/15
MATLAB Code
%% Define Parameters and Initial Conditions
param.g = 9.81; % gravitational acceleration
param.kappa = 0.006; % air drag coefficient
u0 = 35*cos(pi/4);
v0 = 35*sin(pi/4);
%% Animating results
exitCode = ballAnimation(tOut,XOut);
• Suppress “echo”
5
12/17/15
6
12/17/15
• We will learn
• Building arrays
• Colon notations
• Array operations and functions
7
12/17/15
Building Arrays
Array Building Functions
• Recall that we can build arrays as: Command Meaning
ones(m,n) Build m×n matrix of 1’s
>> A = [1, 2; 3 4]; zeros(m,n) Build m×n matrix of 0’s
eye(n) Identity matrix
diag(vec) Create diagonal matrix
• We can also build arrays from diag(A) Diagonal elements of A
rand(m,n) Uniform random number array
existing arrays (if correct size):
randn(m,n) Gaussian Random number array
>> B = [b, c]; magic(m) Magic square matrix
hilb Hilbert matrix
8
12/17/15
9
12/17/15
10
12/17/15
11
12/17/15
12
12/17/15
13
12/17/15
MacLaurin Series
14
12/17/15
15
12/17/15
Scope of Variables
• script shares the variables with workspace from where it was called
16
12/17/15
• All other purposes, you are likely to use scripts (instead of functions)
17
12/17/15
• Other options…
• Plotting data
• Using plot command
• Other options…
19
12/17/15
Plotting
• Log-Log plot
20
12/17/15
MODULE – 1
INTRODUCTION TO MATLAB PROGRAMMING
Dr. Niket Kaisare
Department of Chemical Engineering
IIT–Madras
21
12/17/15
Summary of Module-1
• MATLAB basics
Summary of Module-1
• Execution control
• for and while loops
• if-then statements
• MATLAB files
• Plotting in MATLAB
22
ERRORS AND APPROXIMATIONS
Lec. 2.1: Errors in Numerical Methods
Dr. Niket Kaisare
Department of Chemical Engineering
IIT–Madras
• Just like these devices, real numbers also have a “least count”
Example
n
0. x x x x x ×10
• Floating Point representation of a number:
2
• Example: 23.217 becomes 0. 2 3 2 1 7 ×10
• 23.218 becomes 2
0. 2 3 2 1 8 ×10
• But, 23.2172 remains 2
0. 2 3 2 1 7 ×10
• Thus, the least count of this decimal machine: ~ 0.00001 3
End of Lecture 2.1
• Taylor’s series:
ℎ' AA ℎ-
? 3+ℎ =? 3 + ℎ? A 3 + ? 3 + ⋯+ ? - 3 + B ℎ-C1
2! .!
"
&' &* &-
! = 1+&+ + +⋯+ + B &-C1
2! 3! .!
• The last term implies error in retaining only finite number of terms of the series
MacLaurin Series from 1 to 5
&' &
= & ×
• 1 term: ! " = 1 + & + B &' 2! 2
"D
• 2 terms: ! " = 1 + & + '! + B &* &*
=
&'
×
&
3! 2! 3
"D "F
• 3 terms: ! " ≈ 1 + & + '! + *!
Truncation Error in ea
-2
10
-4
10
-6
-7
10
• Slope = . + 1 10
-8
-9
• Slope is the order of accuracy!!
10
-10
10 -2 -1
10 10
step, a
End of Lecture 2.2
• From definition of ? A 3 :
? 3 +ℎ −? 3 ? 3+ℎ −? 3
? A 3 = lim ⇒ ? A 3 ≈
S→/ ℎ ℎ
B ℎ
• Numerical Differentiation:
? 3+ℎ −? 3
?A 3 = +B ℎ
ℎ
• Truncation error decreases with ℎ
• However, machine precision may determine how small ℎ we can use
• Roundoff error increases with ℎ
Direct vs. Iterative Methods
• Direct methods:
An algorithm (sequence of operations) to “directly” compute a solution
"D "W
• MacLaurin Series: ! " ≈ 1 + & + '!
+⋯+ -!
X "CS YX "
• Numerical derivative: ?A & ≈ S
• Iterative methods:
Improve an initial guess by repeatedly using computational steps until “convergence”
ZC1
1 Z
2
3 = 3 +
2 3 Z
• Use Taylor’s series 10 times with step size of 0.01 to obtain ? 0.1 :
& = 0, ℎ = 0.01, \ = 10
Example: e0.1
Single Term of Taylor’s Series Error decreases as \ increases
• ⋮ • ⋮
• Definitions of error:
• True error: 2 Z = 3 4567 −3 Z
• Notes:
• We used “true error” to analyze errors and approximations in this module
• We used “current approximation error” for stopping an iterative method
Summary
• Direct Methods
X "CS YX "
• Numerical Derivative: ?A & ≈ S
direct application
• Iterative Methods
ZC1 1 Z '
• Héron’s Algorithm: 3 =' 3 +< f until convergence
• Step-wise Methods
• Multi-step Taylor’s series: ! <f CS ≈ ! <f + ℎ! <f until we reach destination
End of Lecture 2.4
NUMERICAL DIFFERENTIATION
Lec. 3.1: Differentiation in Single Variable
Dr. Niket Kaisare
Department of Chemical Engineering
IIT–Madras
Numerical Differentiation
Example
tan −1 (1+10 −4 ) − tan −1 (1) ε = 5e-5
−4
10
"d −1 %
$# tan (x)'& tan −1 (1+10 −4 ) − tan −1 (1−10 −4 )
dx x=1 ε = 2e-9
2 ×10 −4
• Order of accuracy:
• Previous example was done for ℎ = 1067
NUMERICAL DIFFERENTIATION
Lec. 3.2: Differentiation in Single Variable
Dr. Niket Kaisare
Department of Chemical Engineering
IIT–Madras
f ( xi + 2 ) − 2 f ( xi +1 ) + 2 f ( xi −1 ) − f ( xi − 2 )
f ʹʹʹ( xi ) =
h 2
( )
+ O h2
Example-1
• Solve the above using central differences to find ! " # and ! "" #
Example-2
Physical Example
• Consider:
6B
? = @A CD E8./;, @ = 1000, BC = 2500
NUMERICAL DIFFERENTIATION
Lec. 3.3: Partial Derivatives
Dr. Niket Kaisare
Department of Chemical Engineering
IIT–Madras
• Consider:
6B
? = @A CD E8./;, @ = 1000, BC = 2500
X!
= cos #8 A 6[\
X#8
X!
= − sin #8 A 6[\
X#/
A Function of Multiple Variables
• Consider the following function:
#
! S = sin #8 exp −#/ , # = #8
/
• The partial differential (è gradient in Transport Phenomena):
X! X!
]! S = = cos #8 A 6[\ − sin #8 A 6[\
X#8 X#/
hi k8 ℎ k8 ℎ
• To obtain è compute r at: k + 8 and k − 8
hD / 0 / 0
hi k8 0 k8 0
• To obtain è compute r at: k + and k −
hj / ℎ/ / ℎ/
Numerical Integration
Single application
Trapezoidal Rule
Simpson’s 1/3rd Rule
Simpson’s 3/8th Rule
Numerical Integration
• Single application
• Trapezoidal Rule
Numerical Integration
• Single application
• Trapezoidal Rule
• Trapezoidal Rule:
On( (
∫O ! # m# = / ! k + ! k + ℎ
• For Interval-2:
( 1 2 … … n
s/ = /
! k +ℎ + ! k + 2ℎ
a b
a+h
• And so on… è s = s8 + s/ + ⋯ sc
t6O
ℎ=
c
Multiple Applications of Trapezoidal Rule
Example 1
NUMERICAL INTEGRATION
Lec. 3.6: MATLAB Functions and Application
Dr. Niket Kaisare
Department of Chemical Engineering
IIT–Madras
Using functions:
@(x,y,…) nameOfFun(<var list>)
• Usage of MATLAB function:
I = quad(@(x) myFun(x),x);
• A vector…
⎡ 2⎤ 3
• Is an ordered set of scalars x=⎢ ⎥
⎣ 3⎦ 2
• Has “dimension” (# of elements)
2x + 4y = 4 2x + 4y = 2
x + 2y = 1
(3, -1) x + 2y = 1 x + 2y = 1
x-y=4
x + 2y =1
x = 3; y = −1
2 x + 3.999 y = 2.001
x + 2y =1
x = 1; y = 0
2 x + 3.999 y = 2
⎡1 2 ⎤
A=⎢ ⎥ Eigenvalues λ1 = −2 ×10− 4 ; λ2 = 4.99;
⎣2 3.999⎦
Useful MATLAB functions
command Purpose command Purpose
expm Matrix exponent inv Inverse of a matrix
logm Matrix logarithm rank Rank of a matrix
sqrtm Matrix square root cond Condition number
^ Matrix Power norm Norm of a vector/matrix
• With + 2,2 as pivot element, repeat the above steps for 8- and below
• … And so on until we obtain upper triangular matrix
Back-Substitution
> -
• !- = ? -,-
> % @? %,- AB
• !% = ? %,%
Assignment Problem
1 2 2 1 1
2 2 4 2 0
G=
1 3 2 5 2
2 6 5 8 4
End of Lecture 4.2
LINEAR EQUATIONS
Lec. 4.3: LU Decomposition; Partial Pivoting
Dr. Niket Kaisare
Department of Chemical Engineering
IIT–Madras
• In this lecture
• LU Decomposition
• Partial Pivoting
LU Decomposition
•+ = IJ, where
J is matrix obtained after Gauss Elimination, and
1 0 ⋯ 0
I = :%," 1 ⋯ 0
:-," :-,% ⋱ ⋮
Gauss Elimination + Partial Pivoting
• Jacobi:
,N − ∑9QN +N,9 !9 ;
!N;O" =
+N,N
• Gauss-Siedel:
;O"
,N − ∑N@"
9R" +N,9 !9 + ∑SNO" +N,9 !9 ;
!N;O" =
+N,N
Gauss Siedel
http://nptel.ac.in/courses/103106074/8
Gauss Siedel
1 2 2 1 1
2 2 4 2 0
G=
1 3 2 5 2
2 6 5 8 4
Tri-Diagonal Matrix
W" = 100
W" − 2 + : W% + W- = ^ : = 0.04
W% − 2 + : W- + W_ = ^
⋮ ⋮ ^ = −1.0
W"" = 25
Tri-Diagonal Matrix
A Simple Example
To solve the following equation:
2.0 − % + ln % = 0
1
2/7/16
General Setup
Let x be a variable of interest. The objective is to find the value of x
which satisfies the following nonlinear equation:
* % =0
Solution!
2
2/7/16
• Bracketing Methods
• Bisection method
• Regula Falsi
• Open Methods
• Secant method
• Fixed-point iteration
• Newton-Raphson
3
2/7/16
4
2/7/16
• Usage:
xSol = fzero(@(x) funName(x),x0)
• xSol is the resulting solution
• funName is a function file that we provide to calculate * %
• x0=[xL;xH]; is vector of initial guesses
Problem to Solve
5
2/7/16
6
2/7/16
567 5
% =2 %
7
2/7/16
Example
2 − % + ln % = 0
% = 2 + ln (%) % = 9 4:;
0.1586 3.1462
Example 2
5% − 9 4/; = 0
8
2/7/16
9
2/7/16
Newton Raphson
• Popular Method
567 5
* %5
% =% − > 5
* %
Example
10
2/7/16
Newton Raphson
565 5
* %5
% =% − > 5
* %
;
• Has quadratic rate of convergence è @ 567 = @ 5
11
2/7/16
1. Bisection Method
2. MATLAB function fzero
3. Fixed-Point Iteration
4. Newton-Raphson
12
2/7/16
• Usage:
xSol = fsolve(@(x) funName(x),x0)
• xSol is the resulting solution
• funName is a function file that we provide to calculate A B
• x0 initial guess (same dimension as number of variables)
Problem to Solve
13
2/7/16
• Wikipedia: https://en.wikipedia.org/wiki/Lorenz_system
14
2/7/16
1 −1 0
F= 2−D −1 −%
C % −3
15
2/7/16
16
Name : Mr. KATRAVATH SANTHOSH
Rate of
S.
Account Number Account Type Branch Interest Balance
No.
(% p.a.)
Example: Regression
• Given the following data:
Regression:
Obtain a straight line that
best fits the data
1
2/15/16
Example: Interpolation
• Given the following data:
Interpolation:
“Join the dots” and
find a curve passing
through the data.
2
2/15/16
3
2/15/16
4
2/15/16
⎡1 x1 u1 w1 ⎤ ⎡a0 ⎤ ⎡ y1 ⎤
⎢1 x
⎢
⎢% %
2 u2 w2 ⎥ ⎢ a1 ⎥ ⎢ y2 ⎥
%
⎥⎢ ⎥ = ⎢ ⎥
% ⎥ ⎢ a2 ⎥ ⎢ % ⎥
(
Φ = XT X )−1 X T Y
Least Squares Solution
⎢1 x u N wN ⎥⎦ ⎢⎣ a3 ⎥⎦ ⎢⎣ y N ⎥⎦
⎣$&& N&# &&& " ! $#"
X Φ Y
5
2/15/16
Example
• Standard syntax:
phi=lsqcurvefit(@(p,xData) fName(p,xData),p0,xData,yData);
• phi parameter vector
• p0 vector of initial guesses
• xData, yData data arrays with ( rows
• fName provides !:;<=> = ? '; Φ
• lsqcurvefit minimizes the error between !<ABA and !:;<=>
6
2/15/16
7
2/15/16
M 1
ln C = ln D$ + − + S ln J
⏟
N P T
R
8
2/15/16
• Standard syntax:
phi=lsqnonlin(@(p) fName(p),p0);
• phi parameter vector
• p0 vector of initial guesses
9
2/15/16
Interpolation in MATLAB
• Syntax:
yInterpolated = spline(xData,yData,xval);
• xData,yData S×1 data vectors
• yInterpolated values interpolated at xVal (can be vectors)
10
2/15/16
time 00 01 02 03 04 05 06 07 08 09 10 11 12
T 25.6 25.4 25.1 24.9 24.9 25.2 25.9 26.3 27.1 29.3 30.8 31.2 32.1
time 13 14 15 16 17 18 19 20 21 22 23 24
T 31.0 30.3 31.4 30.6 31.8 29.6 28.4 28.1 28.2 27.4 26.8 26.1
time (s) 0 10 20 30 40 50 60 70 80 90
speed 45 32 0 0 7 12 20 15 29 55
11
2/15/16
12
2/22/16
1
2/22/16
(*./ − (*
lim = % &, (
5→) ℎ
t
(*./ = (** + ℎ-
ℎ%(&,
* ()
Numerical methods for ODE-IVP:
Use “best” estimate of slope - to obtain ( &
Example
• ODE–IVP:
• ODE: ( 8 = −2&(
• Initial: ( 0 =1
2
2/22/16
@((*./)
3
2/22/16
• Runge-Kutta Method:
(*./ = (* + ℎ-*
• where, nth-order RK method gives slope as:
-* = A/ B/ + A? B? + ⋯ + AD BD
4
2/22/16
• Heun’s Method
5
(*./ = (* + ? B/ + B?
B/ = @ & * ,(* , B? = @ & * + ℎ, (* + ℎB/
• Midpoint Method
(*./ = (* + ℎ B?
5 5EF
B/ = @ & * ,(* , B? = @ & * + ? , (* + ?
… etc.
5
2/22/16
Syntax of ode45
6
2/22/16
7
2/22/16
8
2/22/16
5
• (*./ = (* + B/ + 2B? + 2BM + BO + N ℎL
P
• B / = @ &*, (*
5 5EF
• B ? = @ &* + ? , (* + ?
5 5EQ
• B M = @ &* + ? , (* + ?
• BO = @ &* + ℎ, (* + ℎB M
9
2/22/16
10
2/22/16
5
• Heun’s Method: (*./ = (* + ? B/ + B? + N ℎM
5
• RK-3 (Std.) Method: (*./ = (* + B/ + 4B? + BM + N ℎO
P
5
• RK-4 (Std.) Method: (*./ = (* + B/ + 2B? + 2BM + BO + N ℎL
P
11
2/22/16
12
2/29/16
Overview
• Module-7 covered ODE in single variable
1
2/29/16
An example
• Model for a damped spring-mass system
" #$ "$
! #+' + ($ = 0
"% "%
• Initial condition: System is stationary @ $ 0 = 1
-
" $0 1
0= '- + ($ , 0 0 = =
"% − - 0 0
!
• Solve using ode45 for ! = 10,' = 5, ( = 15 and until % = 10.
2
2/29/16
3
2/29/16
$ −100 0 $3
" 3
=
"% $
# 0 −0.01 $ #
• Consider:
$ −5.7 1.85 $ 3
" 3
=
"% $
# 13.2 −4.3 $ #
• Solve using Runge-Kutta solver: ode45
• Solve again using implicit solver: ode15s
4
2/29/16
A nonlinear example
5
2/29/16
<= <# =
= > # − ? = − =@ , > = 0.025; ? = 0.1
<% <$
• BC: Rod is held at 100 °C at one end and at =@ = 25 °C at the other end
• IC: Initially, entire rod is uniformly at =@ = 25 °C
6
2/29/16
<= <# =
= > # − ? = − =@ , > = 0.025; ? = 0.1
<% <$
• As in Lecture 4.5, we use central difference formula:
System of ODEs
=#
• Define solution vector 0 = ⋮ and solve using ode45
=I
7
2/29/16
8
2/29/16
Examples Considered
<= <# =
= > # − ? = − =@
<% <$
Examples Considered
<= <# =
= > # − ? = − =@
<% <$
9
2/29/16
Examples Considered
=K − 2=# + =3
• Damped spring-mass system: =# > − ? =# − =@
ℎ#
" =0
!$ 44 + '$ 4 + ($ =K = =M − 2=K + =#
"% > − ? =K − =@
ℎ#
• Van der Pol Oscillator ⋮
44 # 4
$ −; 1− $ $ + $ = 0 ⋮
<= <# =
= > # − ? = − =@
<% <$
Examples Considered
<= <# =
= > # − ? = − =@
<% <$
10
2/29/16
11
2/29/16
12