[Math] Using Runge Kutta 2 on a System of Equations

MATLABordinary differential equationsvectors

So I created a MatLab code to solve an ODE equation, however I'm having a hard time vectorizing everything!

Here is the code as I have it:

% Midpoint Rule = Runge Kutta 2

clear

y(1) = 2;
tmax = 30;
h = 0.01;
nstep = tmax/h;
t = 0:h:tmax;

% rk2 loop

for n = 1:nstep
    k1 = h*fxn(t(n),y(n));
    k2 = h*fxn(t(n)+h/2,y(n)+k1/2);
    y(n+1) = y(n)+k2;
end

% output

plot(t,y,'b')
legend('y: rk2')

And my current function is:

function [dydt] = fxn(t,y)

    dydt = 0.5*y*(1-y/100);

end

I want my new functions (a system of ODEs) to look like this:

function [dydt] = fxn(t,y)

    y1 = y(1);
    y2 = y(2);

    dydt = [y2;-0.5*y1+2.5*y2];

end

I'm not sure how to change the initial conditions vector or the K1, k2, y(n+1) equations to reflect the vector change! Any hints/help would be appreciated.

Best Answer

Note that I have not checked you have implemented the RK2 algorithm correctly. I have just modified the code that you have provided.

You don't need to change very much at all.

You should preallocate (which is good practice) y = zeros(2,nstep+1);, where column n of y is the solution at time n-1.

You need to set the initial condition:

y(:,1) = [value1;value2];

Your expression for k1 needs to change so that the vector of current y values is passed to f:

k1 = h * fxn(t(n), y(:,n));

Your expression for k2 needs to change similarly:

k2 = h * fxn(t(n) + h/2, y(:,n) + k1/2);

And you need to update when you store the solution

y(:,n+1) = y(:,n) + k2;

This will store the solution for y1 in the first row of y and y2 in the second row.

As you store the solution for each timestep as a column vector, you need to ensure that your function fxn returns a column vector.

Related Question