Uploaded by Ismail Mirza

RK CurveFit

advertisement
ME 262
Numerical Analysis Sessional
Dr. Kazi Arafat Rahman
Assistant Professor
Dept. of Mechanical
Engineering, BUET
Objectives
• Ordinary Differential Equations using Runge-Kutta methods
• Curve Fittings
Initial Value Problem
Solve the I.V.P.
dy/dt= t2+y2 with y(0) = 0 over 0  t  1. Use 4th order Runge-Kutta method.
fn.m
function f= fn(t,y)
f = y^2+t^2;
Initial Value Problem
Solve the I.V.P.
dy/dt= t2+y2 with y(0) = 0 over 0  t  1. Use 4th order Runge-Kutta method.
n=input('Enter the number of time
steps');
h=1/n;
y(1)=0;
t=linspace(0,1,n+1);
for i=1:n
k1=h*fn(t(i), y(i));
k2=h*fn(t(i)+h/2, y(i)+k1/2);
k3=h*fn(t(i)+h/2, y(i)+k2/2);
k4=h*fn(t(i)+h, y(i)+k3);
y(i+1)=y(i)+(k1+2*k2+2*k3+k4)*1/6;
end
disp(y);
plot(t,y);
Initial Value Problem – Built-in ODE solver
Solve the I.V.P.
dy/dt= t2+y2 with y(0) = 0 over 0  t  1. Use 4th order Runge-Kutta method.
tspan = [0 1] ; % specify time span
y0 = 0; % specify y0
[t,y] = ode23 ('fn',tspan,y0 ); % now
execute ode23
plot (t,y) % plot t vs y
xlabel ('t')
ylabel ('y')
hold on
[t,y] = ode45 ('fn',tspan,y0 ); % now
execute ode45
plot (t,y); % plot t vs y
xlabel ('t');
ylabel ('y');
Second-order nonlinear ODE
system of first-order equations
Solve using MATLAB
function zdot = fn2 (t,z);
% Call syntax: zdot = fn2
(t,z);
% Inputs are: t = time
%
z = [z (l);z
(2)] = [theta; thetadot]
% Output is: zdot = [z (2) ; w^2*sin z(1)]
wsq = 1.7; % specify a value
of w^2
zdot = [z(2); -wsq*sin(z(1))];
tspan = [0 20] ; z0 = [1;0] ; % assign
values to tspan , z0
[t,z] = ode45 ('fn2', tspan, z0 ); % run
ode23
x = z(:,1); y = z(:,2) ; % x=column 1 of z,
y=column 2
plot (t,x,t,y,':') % plot t vs x and t vs y
xlabel('t' ), ylabel ('x and y') % add axis
labels
figure (2) % open a new figure window
plot (x,y) % plot phase portrait
xlabel ('Displacement'); ylabel
('Velocity');
title ('Phase Plane Plot'); % put a title
Solve using MATLAB
ode23 vs ode45
▪ For solving most initial value problems, use either ode23 or ode45
▪ ode23 is quicker but less accurate than ode45, in general
▪ Actual performance also depends on the problem in hand
Curve Fitting
▪
▪
▪
▪
Straight line fitting: Polynomial curve fitting on the fly – built-in
Curve fitting with polynomial function: polyfit and polyval
Least squares curve fitting
General nonlinear fits – interp1, interp2, interp3, spline, interpft
Let’s do some fun in MATLAB!
Download