简体   繁体   English

在另一个函数内调用函数

[英]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) ? 我怎么能把这个函数作为args传递到toto函数,因为有时我想调用toto(a,b)和其他一些时候toto(a,b,@()myFunc(x,y)

( Answer before question edit: assumes fixed number of inputs to toto ) 问题编辑前的答案:假设输入的固定数量为toto

If you want to call an arbitrary function from within function toto : first define a handle to that function: 如果要从函数toto调用任意函数:首先定义该函数的句柄:

f = @myFunc;

and then pass that handle as input argument to toto , so that you can use it within toto : 然后将该句柄作为输入参数传递给toto ,以便您可以在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). 如果您希望能够同时使用toto(a,b)toto(a,b,f)或类似的函数调用,则需要使用vararginnargin (以及它们的输出副本)。 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). 例如,您可以将其称为x = toto(2,3) (返回x = 5), [xy] = toto(2,3) (返回x = 5,y = []), [xy] = toto(2,3,@(x,y)(x*y)) (返回x = 5,y = 6)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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