Search code examples
matlabsyntaxequationsode45

MATLAB ode45 function 'Too many inputs error'


My function is:

function [tout, yout] = Lorenz (rho, x0)
%define constants
sigma = 10;
beta = 8/3;

%initial conditions
y0 = [x0; 1; 0];

f = @(t, y) [sigma*(y(2)-y(1)); (y(1)*(rho-y(3)))-y(2); (y(1)*y(2)) - (beta*y(3))];

[tout, yout] = ode45(f, [0 100], y0, 'RelTol', 1e-6, 'AbsTol', 1e-8);
end

When I run the function in the command window with

Lorenz(14,0)

I return

Error using Lorenz>@(t,y)[sigma*(y(2)-y(1));(y(1)*(rho-y(3)))-y(2);(y(1)*y(2))-(beta*y(3))]
Too many input arguments.

Any help would be much appreciated.


Solution

  • Although the syntax is not officially documented by MathWorks, the ODE suite does accept the syntax:

    [t,y] = ode45(odefun,tspan,y0,options,extra1,extra2,...);
    

    where options should be a struct created by odeset (not falling inline with the name-value system of other functions) and extra1,extra2,... is any number of extra, solve-constant parameters to be passed to odefun. I imagine it's a hold over from before anonymous functions possessed their own workspace to allow creation-time function parametrization.

    So, since the options you're passing are not part of a struct, ode45 takes the syntax to be

    [t,y] = ode45(odefun,tspan,y0,extra1,extra2,extra3,extra4);
    

    and, via feval, will make the call odefun(t,y,extra1,extra2,extra3,extra4). A minor rewrite using odeset should do the job nicely:

    options      = odeset('RelTol', 1e-6, 'AbsTol', 1e-8);
    [tout, yout] = ode45(f, [0 100], y0, options);