I'd like to create a function that has a variable number of return arguments based on the value of a flag, having a fixed number of input parameters.
[out1, out2] = myFun(inp1, inp2, 'a');
[out1, out2, out3] = myFun(inp1, inp2, 'b');
I tried using varargout but haven't managed to successfully accomplish what I want to do.

 採用された回答

Stephen23
Stephen23 2018 年 11 月 3 日
編集済み: Stephen23 2018 年 11 月 3 日

0 投票

MATLAB returns arguments based on demand, so you can simply define all three of them:
function [out1, out2, out3] = myFun(inp1, inp2)
out1 = 1;
out2 = 2;
out3 = 3;
and then call it with either two or three output arguments. Try it!

5 件のコメント

Gaetano Quattrocchi
Gaetano Quattrocchi 2018 年 11 月 3 日
Thanks Stephen for your quick reply, but this wasn't exactly what I was searching for. Thanks anyway!
Walter Roberson
Walter Roberson 2018 年 11 月 3 日
function varargout = myFun(inp1, inp2, flag)
if strcmpi(flag, 'a')
varargout{1} = 1;
varargout{2} = 2;
elseif strcmpi(flag, 'b')
varargout{1} = 11;
varargout{2} = 12;
varargout{3} = 13;
else
varargout(1:nargout) = {[]};
end
Stephen23
Stephen23 2018 年 11 月 3 日
Or the same without varargin:
function [y1,y2,y3] = myFun(inp1, inp2, flag)
if strcmpi(flag, 'a')
y1 = 1;
y2 = 2;
elseif strcmpi(flag, 'b')
y1 = 11;
y2 = 12;
y3 = 13;
else
[y1,y2,y3] = deal([]);
end
Gaetano Quattrocchi
Gaetano Quattrocchi 2018 年 11 月 3 日
Thank you both for the clear answer!
Walter Roberson
Walter Roberson 2018 年 11 月 3 日
The very minor difference between the varargout version and the y1, y2, y3 version is for cases such as
[A, B, C, D, E, F, G] = myFun(inp1, inp2, 'nonsense')
The varargout version will set all of the outputs to [] but the y1, y2, y3 would error because the 4th output onward were not set.
Both versions would fire an error for
[A, B, C] = myFun(inp1, inp2, 'a')
for not having set the third output.
You could also consider
function varargout = myFun(inp1, inp2)
if nargout == 2
varargout{1} = 1;
varargout{2} = 2;
elseif nargout == 3
varargout{1} = 11;
varargout{2} = 12;
varargout{3} = 13;
else
varargout(1:nargout) = {[]};
end
which detects how many outputs were requested and can do different things depending on the number of outputs.

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

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeData Type Identification についてさらに検索

製品

リリース

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by