Issue using Matlab RK2 Code

495 Views Asked by At

I am trying to approximate the function:

$y'=-3y+6t+5$ with $y(-1)=2e^{3}-1$ and $h$ ranging from $10^{-4}$ to $10^{-1}$ on the interval $-1<t<2$.

I have written the code for the RK2 Method in Matlab as:

function [w, t, h] = rk2(dom, f, w0, h)

 % A naive implementation of RK2 method.
 % Inputs:
 % dom: time domain
 % f: an anonymous function defined by the RHS of original ODE IVP
 % y0: initial value
 % h: step size

T = diff(dom);
N = ceil(T/h);
h = T/N;

t = dom(1):h:dom(2);
w = zeros(N+1, 1);
w(1) = w0;

for i = 1:N
    k1 = h*f(t(i), w(i));
    k2 = h*f(t(i)+h/2, w(i)+k1/2);
    w(i+1) = w(i) + k2; % midpoint method
end

end

Writing the following in to the command window in Matlab:

[w,t,h]=rk2([-1:2], @(t,y) -3*y+6*t+5, 2*exp(3)-1, 10^(-1))

I am getting the following error:

Error using zeros
Size inputs must be scalar.

Error in rk2 (line 15)
w = zeros(N+1, 1);

Could someone please explain what I need to change in order to get this to work?

Many Thanks.