-->

ODE Runge Kutta MATLAB error

2019-01-29 13:56发布

问题:

so I'm trying to create a Runge Kutta function and this is my code :

function [t,U] = RK(f, n, eta, interv)
h = (interv(2)-interv(1))/n;
t = interv(1):h:interv(2);

v(1) = eta(1);
w(1) = eta(2);
for i=1:n
    k1 = f([v(i),w(i)]);
    k2 = f([v(i),w(i)]+h*k1/2); %f(t(i)+h/2, u(:,i)+h*k1/2);
    k3 = f([v(i),w(i)]+h*k2/2);
    k4 = f([v(i),w(i)]+h*k3);

    v(i+1) = v(i) + h*(k1(1)+2*k2(1)+2*k3(1)+k4(1))/6;
    w(i+1) = w(i) + h*(k1(2)+2*k2(2)+2*k3(2)+k4(2))/6;
end
U = [v;w];
end

Where U is a matrix of 2 lines and n+1 columns, here is the problem when I try to execute this function, for example :

RK(sin, 10, [0,1], [5,15])

I get the error not enough input arguments but when I try to execute the code as a script and replacing f by sin every thing works and i get the U matrix Can someon tell what is the solution ?

回答1:

You are using the sin as a function handle. Just add the @ symbol and you're set.

RK(@sin, 10, [0,1], [5,15])