MATLAB: Variable number of outputs

cell arraymatlab functionoutputvariable

I want to build a matlab function with outputs whose number/length is variable. Below is my code, which somehow returns an error:
function varargout=polyargout(x)
if x==1
nargout=1;
varargout{1}=1;
elseif x==2
nargout=2;
for i=1:x
varargout{i}=magic(i);
end
end
Basically one doesn't know how many outputs to return until running the function. To call the function, I wish to use:
y=polyargout(1) to get y=1
y=polyargout(2) to get y=[magic(1),magic(2)]

Best Answer

It appears that you want to do something like this:
function out = polyargout(x)
if x>1
out = arrayfun(@magic, 1:x, 'uniform', 0);
else
out = 1;
end
end
And tested:
>> polyargout(1)
ans = 1
>> C = polyargout(3);
>> C{:}
ans =
1
ans =
4 3
1 2
ans =
8 1 6
3 5 7
4 9 2
As noted in my earlier comments, although you asked about "variable number of outputs", what you showed and requested is just one output (either a numeric array or a cell array of numeric arrays, depending on the value of x): "To call the function, I wish to use:"
y=polyargout(1) to get y=1
y=polyargout(2) to get y=[magic(1),magic(2)]