Introduction To Programming in MATLAB: Lecture 3: Solving Equations and Curve Fitting
Introduction To Programming in MATLAB: Lecture 3: Solving Equations and Curve Fitting
094
Introduction to programming in MATLAB
Ankit Patel
Danilo Šćepanović
IAP 2008
Outline
• Given a matrix
» mat=[1 2 -3;-3 -1 1;1 -1 1];
System 1:
x+4y=34
-3x+y=2
System 2:
2x-2y=4
-x+y=3
3x+4y = 2
Exercise: Linear Algebra
• plot the fitted polynomial on the same plot, using the same
x values and a red line
Exercise: Polynomial Fitting
» x=fminbnd(@(x) (cos(exp(x))+x^2-1),-1,2);
Optimization Toolbox
function y = myFun(x)
y=cos(4*x).*sin(10*x).*exp(-abs(x));
» x=0:0.01:2*pi; 0.6
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
• 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]
ODE Function: viewing results
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
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
» function dydt=odefun(t,y)
» dydt=-t*y/10;
» [t,y]=ode45(‘odefun’,[0 10],10);
» plot(t,y);
End of Lecture 3