Cannot pass function handle as an argument of a fu

2019-08-31 01:20发布

I'm new to Matlab and I'm trying to write custom function in matlab that would take function handle as one of its arguments. I'm getting this error all the time:

Error using subsindex
Function 'subsindex' is not defined for values of class 'function_handle'.

Trying to debug I performed following test: I run command x = fminbnd(@humps, 0.3, 1). I proceeded as expected - I got result x = 0.6370. So I created custom function called train and I copied ALL the code of function fminbnd to the file train.m. The only thing that I changed is the name, so that code of functions fminbnd and train is now identical except for the names.

Now I run both functions with the same argument and the custom function throws error while original fminbnd returns correct answer. Here is the code:

>> x = fminbnd(@humps, 0.3, 1)

x =

    0.6370

>> x = train(@humps, 0.3, 1)
Error using subsindex
Function 'subsindex' is not defined for values of class 'function_handle'.

Here is header of function train (everything else is copied from fminbnd):

function [xf,fval,exitflag,output] = train(funfcn,ax,bx,options,varargin)

Where is the problem?

2条回答
神经病院院长
2楼-- · 2019-08-31 01:49

Instead of duplicating the whole fminbnd function, try:

function varargout = myfminbnd(varargin)
    varargout = cell(1,nargout(@fminbnd));
    [varargout{:}] = fminbnd(varargin{:});
end

this will work as an "alias" to the existing function:

>> fminbnd(@(x)x.^3-2*x-5, 0, 2)
ans =
       0.8165

>> myfminbnd(@(x)x.^3-2*x-5, 0, 2)
ans =
       0.8165

(you can get the other output arguments as well)

查看更多
Explosion°爆炸
3楼-- · 2019-08-31 02:02

Doing a which train showed me that there is a function in the neural network toolbox of the same name.

/Applications/MATLAB_R2009b.app/toolbox/nnet/nnet/@network/train.m  % network method

You may be running the nnet train.m rather than the one you think you're running. Are you in the directory containing your train.m? When I made sure I was in the right directory, I got it to work:

>> which train
/Users/myuserid/train.m

>> x = train(@humps,0.3,1)

x =

    0.6370

Maybe you can name your file something else like myfminbnd.m instead?

查看更多
登录 后发表回答