Search code examples
matlabodedifferential-equationsfunction-handleode45

Error when passing arguments to function handles


Suppose we have the following function:

function f=lorenz(t,x,a,b,c)
    % solve differential equation like this
    %dx/dt=a*(y-x)
    %dy/dt=-x*z+b*x-y
    %dz/dt=xy-c*z/3
    f=zeros(3,1);% preallocate result
    f(1)=a*(x(2)-x(1));
    f(2)=-x(1)*x(3)+b*x(1)-x(2);
    f(3)=x(1)*x(2)-c*x(3)/3;
    end

For running this program, let us use the following test file:

% test program
x0=[-2 -3.5 21];% initial  point
a=input(' enter first coefficient : ');
b=input(' enter second coefficient: ');
c=input(' enter third coefficient : ');
[t,x]=ode45(@(x) lorenz(x,a,b,c),[0 10],x0);
plot(t,x(:,1),'r'); 
title(' solution of x part');
grid on

I have tried passing arguments to the function handle,

test_program
 enter first coefficient : 10
 enter second coefficient: 28
 enter third coefficient : -8

but it gives me the following error:

Error using @(x)lorenz(x,a,b,c)
Too many input arguments.

Error in odearguments (line 87)
f0 = feval(ode,t0,y0,args{:});   % ODE15I sets args{1} to yp0.

Error in ode45 (line 113)
[neq, tspan, ntspan, next, t0, tfinal, tdir, y0, f0, odeArgs, odeFcn, ...

Error in test_program (line 6)
[t,x]=ode45(@(x) lorenz(x,a,b,c),[0 10],x0);

one solution involves using global variables, like this:

function f=lorenz(t,x)
    % solve differential equation like this
    %dx/dt=a*(y-x)
    %dy/dt=-x*z+b*x-y
    %dz/dt=xy-c*z/3
    global a
    global b
    global c
    f=zeros(3,1);% preallocate result
    f(1)=a*(x(2)-x(1));
    f(2)=-x(1)*x(3)+b*x(1)-x(2);
    f(3)=x(1)*x(2)-c*x(3)/3;
    end

but then it takes too long to run.

How else can I fix this issue? What I want is to pass different arguments, if I write inside code something like this

a=input('enter the coefficient : ')

then this will be repeated several times.


Solution

  • Don't use global variables.

    The fix is very simple, add the t as input too:

    [t,x] = ode45(@(t,x) lorenz(t,x,a,b,c),[0 10],x0);