Professional Documents
Culture Documents
MIT6 094IAP10 Lec03
MIT6 094IAP10 Lec03
094
Introduction to programming in MATLAB
Danilo Šćepanović
IAP 2008
Homework 2 Recap
• Given a matrix
» mat=[1 2 -3;-3 -1 1;1 -1 1];
¾ System 1:
x + 4 y = 34
−3 x + y = 2
¾ System 2:
2x − 2 y = 4
−x + y = 3
3x + 4 y = 2
Exercise: Linear Algebra
• Plot the fitted polynomial on the same plot, using the same
x values and a red line
Exercise: Polynomial Fitting
2
• Evaluate y = x for x=-4:0.1:4.
» x=-4:0.1:4;
» y=x.^2;
» x=fminbnd(@(x) (cos(exp(x))+x^2-1),-1,2);
Optimization Toolbox
0.4
» y=sin(x); 0.2
» dydx=diff(y)./diff(x); 0
-0.4
-0.6
» dm=diff(mat,1,2)
¾ first difference of mat along the 2nd dimension, dm=[2 2;4 -2]
¾ see help for more details
¾ The opposite of diff is the cumulative sum cumsum
• 2D gradient
» [dx,dy]=gradient(mat);
Numerical Integration
• Using the correct ODE solver can save you lots of time and
give more accurate results
» ode23
¾ Low-order solver. Use when integrating over small intervals
or when accuracy is less important than speed
» ode45
¾ High order (Runge-Kutta) solver. High accuracy and
reasonable speed. Most commonly used.
» ode15s
¾ Stiff ODE solver (Gear's algorithm), use when the diff eq's
have time constants that vary by orders of magnitude
ODE Solvers: Standard Syntax
¾ ODE file:
– y has [A;B]
– dydt has
[dA/dt;dB/dt]
Chem reaction
1
A
0.9 B
0.8
0.7
Amount of chemical (g)
0.6
0.5
0.4
0.3
0.2
0.1
0
0 0.05 0.1 0.15 0.2 0.25 0.3 0.35 0.4 0.45 0.5
Time (s)
Higher Order Equations
• Must make into a system of first-order equations to use
ODE solvers
• Nonlinear is OK!
• Pendulum example:
g
θ&& + sin (θ ) = 0
L
g
θ&& = − sin (θ )
L
let θ& = γ
g
γ& = − sin (θ )
L
v ⎡θ ⎤
x=⎢ ⎥
⎣γ ⎦
v
dx ⎡θ& ⎤
=⎢ ⎥
dt ⎣γ& ⎦
Courtesy of The MathWorks, Inc. Used with permission.
Plotting the Output
angle (rad) 2
-2
-4
-6
-8
0 1 2 3 4 5 6 7 8 9 10
Plotting the Output
4
Velocity is greatest
2 when theta=0
Velocity
-2
Velocity=0 when -4
-8
-3 -2 -1 0 1 2 3
Position
ODE Solvers: Custom Options
6
y(t)
0
0 1 2 3 4 5 6 7 8 9 10
Time
End of Lecture 3
For information about citing these materials or our Terms of Use, visit: http://ocw.mit.edu/terms.