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.

 Accepted Answer

Stephen23
Stephen23 on 3 Nov 2018
Edited: Stephen23 on 3 Nov 2018
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 Comments

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.

Sign in to comment.

More Answers (0)

Categories

Products

Release

R2018b

Community Treasure Hunt

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

Start Hunting!