For this we will be combining while and if control structures together. Using MA
ID: 667384 • Letter: F
Question
For this we will be combining while and if control structures together. Using MATLAB.
• Write a pseudocode (pen and paper) algorithm that solves the ODE y 0 = f(t, y) using Euler’s method.
• Convert this algorithm into MATLAB syntax, as the function euler method .
• Your inputs should be the start time t0, the end time tend, the function f, an initial condition y0 and an initial step size h.
• If h × f(t, y) at any point exceeds 1, your function should halve the step size h.
• Equally, if h×f(t, y) at any point drops below 0.01, your function should double the step size h.
• You should also make sure that the final solution step doesn’t ‘overshoot’ tend. (i.e. change h during the final step to exactly reach tend).
• Your MATLAB code should use the function header below, and be well-commented with a sensible layout.
• Include your pseudocode algorithm, as well as the MATLAB code. Also include a discussion of when the could could break, or give incorrect outputs (you DO NOT need to design your code to avoid these).
Explanation / Answer
%
function [ts, ys] = odemeul (rhsfun, tspan, y0, options, varargin)
try, h=options.(matchfieldname(options, 'InitialStep'));
catch, error(['Option InitialStep must be supplied']); end
nsteps = ceil ((tspan(2) - tspan(1)) / h);
ts = zeros(nsteps+1,1);
ys = zeros(nsteps+1,length(y0));
t = tspan(1);
ts(1) = t;
ys(1,:) = conj (y0');
for step = 2:nsteps+1
if (ts(step-1) + h >tspan(2)), h=tspan(2)-ts(step-1); end
ts(step) = ts(step-1) + h;
ys(step,:) = (feval ('MEuler', rhsfun, h, ts(step-1), ys(step-1,:)', varargin{:}))';
end
ys=conj(ys);
return;
end
%
% Do one Modified Euler step for the equation dy/dt = f(t,y).
%
% y_n+1 = y_n + h/2 * (f(t_n+1, y_n+1) + f(t_n, y_n))
%
% which is approximated as
%
% y_n+1 = y_n + h/2 * (f(t_n+1, y_p) + f(t_n, y_n)) ,
%
% where y_p = y_n + h * f(t_n, y_n)
%
% Arguments:
% rhsfun = rhs function f(t,y)
% h = step length
% tn = time t_n
% yn = function value y_n
%
function [yn1] = MEuler (rhsfun, h, tn, yn, varargin)
tp = tn + h;
fn = feval (rhsfun, tn, yn, varargin{:});
yp = yn + h * fn;
yn1 = yn + h/2 * (fn + feval (rhsfun, tp, yp, varargin{:}));
end
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.