简体   繁体   中英

Cannot pass function handle as an argument of a function

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?

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?

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM