简体   繁体   中英

Call function inside another function

I have a function

function toto(a,b)

    [out,~] = evalc(a)
    % here I would like to call another function 

    myFunc(x,y,file);        
end

How could I pass this function as args to toto function as sometimes I want to call toto(a,b) and some other times toto(a,b,@()myFunc(x,y) ?

( Answer before question edit: assumes fixed number of inputs to toto )

If you want to call an arbitrary function from within function toto : first define a handle to that function:

f = @myFunc;

and then pass that handle as input argument to toto , so that you can use it within toto :

function toto(a,b,f)

   [out,~] = evalc(a)

   f(x,y,file); %// call function whose handle is f        

end 

Define your function with an input to pass a function handle:

function toto(a,b,fun)
...
% You must know how many inputs and outputs to expect
% but nargin and nargout do work for function handles
% so you can handle different cases if needed.
[y1,y2,...] = fun(x1,x2,...);
...

Call the function and pass in a handle to the function:

toto(a,b,@FunName)

Or:

FunHandle = @FunName;
toto(a,b,FunHandle)

You can pass in additional parameters by using an anonymous function:

Param = 'FileName';
AnonFunHandle = @(x1,x2)FunName(x1,x2,Param);
toto(a,b,AnonFunHandle)

If you want to be able to use both the toto(a,b) and toto(a,b,f) or similar function calls, you need to use varargin and nargin (and their output counterparts). Here is a very basic example; it ignores any more than two outputs or any more than three inputs, and does not do any input checking etc.

function [vargout] = toto(a,b,varargin)

if nargin >2
    func = vargin{1};
    fout = func(a,b);
else
    fout = []  % if no third argument is given returns empty
end

if nargout > 0
    varargout{1} = a+b;
end

if nargout > 1
    varargout{2} = fout;
end

end

So for example you can call this as x = toto(2,3) (returns x = 5), [xy] = toto(2,3) (returns x = 5, y = []), [xy] = toto(2,3,@(x,y)(x*y)) (returns x = 5, y = 6).

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