将参数传递给函数句柄

时间:2017-02-19 21:08:20

标签: matlab ode differential-equations function-handle ode45

假设我们有以下功能:

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

要运行此程序,我们使用以下测试文件:

% 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

我试过将参数传递给函数句柄

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

但是它给了我以下错误:

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);

一个解决方案涉及使用全局变量,如下所示:

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

然后运行需要很长时间。

我还能如何解决这个问题?我想要的是传递不同的参数,如果我在代码中写这样的

a=input('enter the coefficient : ')

然后这将重复几次。

1 个答案:

答案 0 :(得分:3)

不要使用全局变量。

修复非常简单,也可以添加make_unique<U[N]>作为输入:

t