get number of output arguments of a function handle

20 ビュー (過去 30 日間)
Alwin Förster
Alwin Förster 2022 年 1 月 4 日
回答済み: Steven Lord 2022 年 1 月 4 日
Is there a better way to get the number of output arguments (should be one or two) of a function handle than this:
a = 1;
b = 2;
x0 = 0;
fun = @(x) function_file(x,a,b);
try
[f1,f2] = fun(x0);
nout = 2;
catch
nout = 1;
end
It should also work if the function is:
fun = @(x) a*x.^b;
Therefore catching the name 'function_file' using functions(fun) and then use nargout('function_file') is not an option.
Thanks in advance!
Alwin

採用された回答

Steven Lord
Steven Lord 2022 年 1 月 4 日
Calling nargout on the function handle itself may give an answer.
nargout(@sin) % The sin function returns 1 output
ans = 1
But it may not be possible to tell from the function handle with how many outputs it can be called.
nargout(@size) % Can be called with an arbitrary number of output arguments
ans = -1
I believe calling nargout on an anonymous functions always returns -1 because MATLAB can't tell with how many output arguments the code that makes up the body of the anonymous function can be called until you actually call it.
f = @(x) svd(x);
nargout(f)
ans = -1
A = magic(4);
% Call f with 1 output
s = f(A)
s = 4×1
34.0000 17.8885 4.4721 0.0000
% Call f with three outputs
[u, s, v] = f(A)
u = 4×4
-0.5000 0.6708 0.5000 -0.2236 -0.5000 -0.2236 -0.5000 -0.6708 -0.5000 0.2236 -0.5000 0.6708 -0.5000 -0.6708 0.5000 0.2236
s = 4×4
34.0000 0 0 0 0 17.8885 0 0 0 0 4.4721 0 0 0 0 0.0000
v = 4×4
-0.5000 0.5000 0.6708 -0.2236 -0.5000 -0.5000 -0.2236 -0.6708 -0.5000 -0.5000 0.2236 0.6708 -0.5000 0.5000 -0.6708 0.2236

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeProgramming Utilities についてさらに検索

製品


リリース

R2020b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by