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.
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 columnnofyis the solution at timen-1.You need to set the initial condition:
Your expression for
k1needs to change so that the vector of currentyvalues is passed tof:Your expression for
k2needs to change similarly:And you need to update when you store the solution
This will store the solution for
y1in the first row ofyandy2in the second row.As you store the solution for each timestep as a column vector, you need to ensure that your function
fxnreturns a column vector.