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):

  1. A function dydt that defines the ODE to be solved. Your Heun function should accommodate optional parameter inputs to the dydt function.
  2. 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.
  3. The initial condition for y.
  4. 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.
  5. Varargin to accept any optional parameters needed to evaluate the dydt function.

Your function should output the following (in order):

  1. 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

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!