

Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!


Derive the Euler discretization scheme for a first order ODE, and complete its Matlab implementation:
function [t,y] = odeEuler(diffeq,tn,h,y0) % Input: diffeq = (string) name of the m-file that evaluates % the right hand side of the ODE % tn = stopping value of the independent variable % h = stepsize for advancing the independent variable % y0 = initial condition for the dependent variable % % Output: t = vector of independent variable values: t(j) = (j-1)*h % y = vector of numerical solution values at the t(j)
t = (0:h:tn)โ; % Column vector of elements with spacing h n = length(t); % Number of elements in the t vector y = y0*ones(n,1); % Preallocate y for speed
for j= ...
y(j) = ... + h*feval(diffeq, ... );
end
Solution:
function [t,y] = odeEuler(diffeq,tn,h,y0)
t = (0:h:tn)โ; % Column vector of elements with spacing h n = length(t); % Number of elements in the t vector y = y0*ones(n,1); % Preallocate y for speed
for j=2:n y(j) = y(j-1) + h*feval(diffeq,t(j-1),y(j-1)); end
MAE316 QUIZ October 25, 2007
Complete Matlab implementation of the midpoint method:
function [t,y] = odeMidpt(diffeq,tn,h,y0) % % Input: diffeq = (string) name of the m-file that evaluates the right % hand side of the ODE written in standard form % tn = stopping value of the independent variable % h = stepsize for advancing the independent variable % y0 = initial condition for the dependent variable % % Output: t = vector of independent variable values: t(j) = (j-1)*h % y = vector of numerical solution values at the t(j)
t = (0:h:tn)โ; % Column vector of elements with spacing h n = length(t); % Number of elements in the t vector y = y0*ones(n,1); % Preallocate y for speed h2 = h/2; % Avoid repeated evaluation of this constant
for j= ...
k1 = ...
k2 = ...
y(j) = ...
end
Solution:
function [t,y] = odeMidpt(diffeq,tn,h,y0)
t = (0:h:tn)โ; % Column vector of elements with spacing h n = length(t); % Number of elements in the t vector y = y0*ones(n,1); % Preallocate y for speed h2 = h/2; % Avoid repeated evaluation of this constant
for j=2:n k1 = feval(diffeq,t(j-1),y(j-1)); k2 = feval(diffeq,t(j-1)+h2,y(j-1)+h2k1); y(j) = y(j-1) + hk2; end
MAE316 QUIZ October 25, 2007