繁体   English   中英

在另一个函数内调用函数

[英]Call function inside another function

我有一个功能

function toto(a,b)

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

    myFunc(x,y,file);        
end

我怎么能把这个函数作为args传递到toto函数,因为有时我想调用toto(a,b)和其他一些时候toto(a,b,@()myFunc(x,y)

问题编辑前的答案:假设输入的固定数量为toto

如果要从函数toto调用任意函数:首先定义该函数的句柄:

f = @myFunc;

然后将该句柄作为输入参数传递给toto ,以便您可以在toto使用它:

function toto(a,b,f)

   [out,~] = evalc(a)

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

end 

使用输入定义函数以传递函数句柄:

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,...);
...

调用函数并传入函数的句柄:

toto(a,b,@FunName)

要么:

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

您可以使用匿名函数传递其他参数:

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

如果您希望能够同时使用toto(a,b)toto(a,b,f)或类似的函数调用,则需要使用vararginnargin (以及它们的输出副本)。 这是一个非常基本的例子; 它忽略任何两个以上的输出或任何三个以上的输入,并且不进行任何输入检查等。

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

例如,您可以将其称为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