Question
MATLAB CODE: Write a function to implement Heun's method with an option to iterate the corrector equation to a specified stopping criterion. Your function need
MATLAB CODE:
Write a function to implement Heun's method with an option to iterate the corrector equation to a specified stopping criterion. Your function need only work for a single ODE (not a system) and should accept the following inputs (in order):
- A function dydt that defines the ODE to be solved. Your Heun function should accommodate optional parameter inputs to the dydt function.
- An evenly spaced time vector that defines the step size, h for the integration (by its increment) and the time span (first and last values) over which the IVP is to be integrated.
- The initial condition for y.
- A stopping criterion for the corrector iteration. If the stopping criterion is left blank, your function should default to implementing Heun's method withoutiterating the corrector equation.
- Varargin to accept any optional parameters needed to evaluate the dydt function.
Your function should output the following (in order):
- A column vector of y values corresponding to the input time vector.
* I know my code doesn't work right now but I also know its got the right idea, please help me keep as much of the same format as possible to get the code working, thank you!
Code:
function [y] = student_solution(dydt, time, y0, es, varargin)
% Need atleast 4 input arguments
if nargin<3
error('at least 3 input arguments required')
end
% if nargin<3||isempty(es), es=1e-5;end
n = length(time);
h = time(end) - time(end-1);
y = y0*ones(n,1);
if isempty(es)
for i = 1:n-1
y(i+1) = y(i) + dydt(time(i),y(i),varargin{:})*h;
end
else
for i = 1:n-1
y_pre(i+1) = y(i) + dydt(time(i),y(i),varargin{:})*h;
ea = es + 1;
count = i;
while abs(ea) > es
y_cor(count+1) = y_pre(count+1);
ycor_new(count+1) = y(count) + ((dydt(time(count),y(count),varargin{:})+dydt(time(count+1),y_cor,varargin{:}))/2)*h;
count = count + 1;
y_pre(count+1) = y(count) + dydt(time(count),y(count),varargin{:})*h;
ea = abs((ycor_new-y_cor)/ycor_new);
end
y = ycor_new;
end
end
end
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started