How to get all outputs of a function in a cell array

I created a function that has a different number of outputs depending on the inputs. I store the outputs into a cell, varargout. When I call the function to try and get the output, I only get the first element of the cell.
function varargout = testfunc(a,b)
varargout = cell(1,a);
for i = 1:a
varargout{i} = b;
end
end
t = testfunc(3,2)
t =
2

 Accepted Answer

"varargout" is an output variable in a function definition statement that enables the function to return any number of output arguments. This specific variable name works differently than others. Each element stored in "varargout" is its own output argument and it is not a cell.
For more information on "varargout" please see the following link:
If you would like the output to be a single output that is a cell array with multiple elements, instead of multiple separate outputs, simply use a different variable.
function vout = testfunc2(a,b)
vout = cell(1,a);
for i = 1:a
vout{i} = b;
end
end
t = testfunc2(3,2)
t =
1×3 cell array
{[2]} {[2]} {[2]}

More Answers (0)

Products

Release

R2018a

Community Treasure Hunt

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

Start Hunting!