如何在Matlab中传递函数作为参数

时间:2012-08-22 10:23:39

标签: matlab

我在m文件中定义了这个函数:

function[it,xvect,xdif,fx]=bisez(a,b,nmax,toll,fun)
it=-1;
xvect=[];
xdif=[];
fx=[];
err=toll+1;

while(it<nmax && err>toll)
x=(b+a)/2;
  if(fun(x)==0)
    err=0;
  else
    err=abs(b-a)/2;
  end
it=it+1;
xvect=[xvect;x];
xdif=[xdif;err];
fx=[fx:fun(x)];
  if(fun(x)*fun(a)>0)
    a=x;
  else
    b=x;
  end;
end;
if(it<nmax)
  fprintf('Convergence computed at step k:%d\n',it);
else
  fprinf('Iteration limit reached: %d\n',it);
end
  fprintf('Computed root: %-12.8f\n',xvect(it+1));
return

然后,如果我尝试使用这些命令调用它:

fun=@(x)exp(x);
a=1;
b=1.5;
nmax=1000;
toll=2;
bisez(a,b,nmax,toll,fun)

我收到此错误:

??? Undefined function or method 'bisez' for input arguments of type 'function_handle'.

我错过了什么?

PS:我正在使用Matlab 2007b

1 个答案:

答案 0 :(得分:5)

运行它时,它似乎不在您的PATH中。

如果我从PATH运行它,我得到:

>> bisez(a,b,nmax,toll,fun)
   Convergence computed at step k:0
   Computed root: 1.25000000  

   ans =

        0

在我的路径之外:

>> bisez(a,b,nmax,toll,fun)
   Undefined function 'bisez' for input arguments of type 'function_handle'.
相关问题