Hello, I am a first year engineering student and so my coding/Matlab foundation isn't that solid, so please don't delve into higher level matlab coding practises when explaining >_< thanks.

Here's the code for Heun's method. Everything but the bolded parts I do not get.

I don't get what the bolded parts are doing, and what purpose they serves in the code.

Thanks for helping me out Really do appreciate it.

function [t,y] = heun(dydt,tspan,y0,h)

% [t,y] = heun(dydt,tspan,y0,h):

% uses Heun's method to solve an ODE

% input:

% dydt = function handle of the ODE, f(t,y)

% tspan = [<initial value>, <final value>] of independent variable

% y0 = initial value of dependent variable

% h = step size

% output:

% t = vector of independent variable

% y = vector of solution for dependent variable

% Input Validation: tspan

if ~(tspan(2)>tspan(1))

error('upper limit must be greater than lower')

end

% Create all independant values, t

t = (tspan(1):h:tspan(2))';

n = length(t);

% if necessary, add an additional t so that range goes up to tspan(2)

if t(n)<tspan(2)

t(n+1) = tspan(2);

n = n+1;

end

% Implement Heun's method

y = y0*ones(n,1); % Preallocate y to improve efficiency

for i = 1:n-1

% Heun's method

yend = y(i) + dydt(t(i),y(i))*(t(i+1)-t(i));

y(i+1) = y(i) + (dydt(t(i),y(i))+dydt(t(i+1),yend))/2*(t(i+1)-t(i));

end