I'm still confused about your initial conditions and what y0 and y1 are. But let's back up a bit.
For a 2nd order ODE, your state vector will have 2 elements. E.g., if y is your state then y(1) could be position and y(2) could be velocity. This looks like the setup you have in your FunctionC( ) above. So for that case, the states in your RK4 solver have to reflect this and be 2-element vectors, not scalars. So that y pre-allocation needs to have 2 rows, not 1. And all the downstream indexing needs to account for this as well. E.g., something like this if we assume that those y0 and y1 values are the initial values at the x0 time (CAUTION: Not checked):
function [x, y] = FunctionBeta_Executor(F,h,x0,x1,y0,y1)
x = x0:h:x1;
y = zeros(2,length(x));
y(1,1) = y0;
y(2,1) = y1;
for i=1:(length(x)-1)
k1 = F( x(i) , y(:,i) );
k2 = F( x(i) + 0.5*h , y(:,i) + 0.5*h*k1 );
k3 = F( x(i) + 0.5*h , y(:,i) + 0.5*h*k2 );
k4 = F( x(i) + h , y(:,i) + h*k3 );
y(:,i+1) = y(:,i) + (1/6)*( k1 + 2*k2 + 2*k3 + k4 )*h;
end
figure, plot(x, y(1,:))
end
Note also how much easier it is to read (and debug) when you use spacing!
Best Answer