簡體   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