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
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 个评论

Thanks Stephen for your quick reply, but this wasn't exactly what I was searching for. Thanks anyway!
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
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
Thank you both for the clear answer!
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 Exchange 中查找有关 Calendar 的更多信息

产品

版本

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by