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!
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
Gaetano Quattrocchi
Gaetano Quattrocchi 2018년 11월 3일
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에서 Data Type Identification에 대해 자세히 알아보기

제품

릴리스

R2018b

질문:

2018년 11월 3일

댓글:

2018년 11월 3일

Community Treasure Hunt

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

Start Hunting!

Translated by