How to check if one of output variables is not called

12 ビュー (過去 30 日間)
KAE
KAE 2019 年 8 月 16 日
編集済み: KAE 2019 年 8 月 20 日
If I have a function which can return multiple outputs, how can I tell from inside the function that some of the output variables are not called? One application is skipping a long calculation of an unused output variable.
Here is a non-working example. Can it be made to work?
% This would perform both calculations
[addIt, multIt] = test_empty_function_outputs1(2,3);
% This would only perform the addition to get the 1st output
[addIt, ~] = test_empty_function_outputs1(2,3);
% This would only perform the multiplication to get the 2nd output
[~, multIt] = test_empty_function_outputs1(2,3);
function varargout = test_empty_function_outputs1(x,y)
if ~isempty(varargout{1}) % Only calculate if 1st output is called
% Gives an error: Undefined function or variable 'varargout'
varargout{1} = x+y;
end
if ~isempty(varargout{2}) % Only calcluate if 2nd output is called
varargout{2} = x*y;
end

採用された回答

Stephen23
Stephen23 2019 年 8 月 16 日
編集済み: Stephen23 2019 年 8 月 16 日
You can use nargout to detect how many output arguments are requested:
if nargout>0
varargout{1} = x+y;
end
if nargout>1
varargout{2} = x*y;
end
There is no direct way to detect which of those outputs are allocated to variables:
  2 件のコメント
KAE
KAE 2019 年 8 月 19 日
編集済み: KAE 2019 年 8 月 19 日
Sorry I missed those answers. Checking for non-called outputs seems useful so I will put in a feature request.
KAE
KAE 2019 年 8 月 20 日
編集済み: KAE 2019 年 8 月 20 日
In response to my feature request, Matlab support provided a workaround adding some flag arguments to control which output should be calculated:
function [out1, out2, out3] = example(in1, in2, flag)
%define all outputs%
out1 = -1;
out2 = -1;
out3 = -1;
%calculate the output according to flag%
if flag(1) == 1
out1 = 1;
end
if flag(2) == 1
out2 = 1;
end
if flag(3) == 1
out3 = 1;
end
end
To invoke the function:
%here, skip output2%
[a, ~, c] = example(11, 22, [1,0,1])

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeArgument Definitions についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by