Is it possible to use a function with 2 outputs and sometimes with 4 outputs?

2 ビュー (過去 30 日間)
Mr M.
Mr M. 2018 年 7 月 26 日
回答済み: OCDER 2018 年 7 月 26 日
And how to order the output variables? [x1,x2,x3,x4] = f(); or [x4,x3,x2,x1] = f();
  2 件のコメント
Stephen23
Stephen23 2018 年 7 月 26 日
"Is it possible to use a function with 2 outputs and sometimes with 4 outputs?"
Yes.
"And how to order the output variables?"
The order of the output arguments is determined by how they are defined in the function itself. What you call them in the calling workspace is totally irrelevant.
Adam Danz
Adam Danz 2018 年 7 月 26 日
Also see
help varargout

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

採用された回答

OCDER
OCDER 2018 年 7 月 26 日
See this example function as a starting point for how to make functions with variable input/output, and to do a input/output check, etc.
% EXAMPLE
% >> [x1, x2, x3, x4] = myfun(0)
%
% or, to prevent habit of dynamically named variable issue x1, x2, ....,
% use a cell output like this:
%
% >> x = cell(1, 4);
% >> [x{:}] = myfun(0)
% "x1" is accessed via "x{1}"
%
function varargout = myfun(varargin)
fprintf('There are %d inputs\n', nargin);
fprintf('There are %d outputs\n', nargout);
if nargin < 1
error('%s: Must have at least 1 input.', mfilename);
end
if ~ismember(nargout, [2, 4])
error('%s: Must have 2 or 4 outputs.', mfilename);
end
varargout{1} = varargin{1};
varargout{2} = varargin{1} + 1;
varargout{3} = varargin{1} + 2;
varargout{4} = varargin{1} + 3;

その他の回答 (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