# Return multiple results from a function in one variable

45 views (last 30 days)
MathWorks Support Team on 11 Aug 2017
Edited: Stephen Cobeldick on 30 Sep 2020 at 8:34
I have a function called "ols2" that calculates 12 different values. Is there some way I can call the function program without listing all 12 of the return values? In other words, I want to avoid having to say
[p1,p2,p3 p4,p5,p6,p7,p8,p9,p19,p11,p12] = ols2(x,y)

MathWorks Support Team on 30 Sep 2020 at 4:00
Edited: MathWorks Support Team on 30 Sep 2020 at 7:51
One way to return multiple variables from a function is to group them in a struct. Here is an example function:
function res = foo()
res.x=1;res.y = 2;
end
You can then call the function by writing
>> my_res = foo()

Stephen Cobeldick on 30 Sep 2020 at 8:06
Edited: Stephen Cobeldick on 30 Sep 2020 at 8:34
"I have a function called "ols2" that calculates 12 different values. Is there some way I can call the function program without listing all 12 of the return values?"
The simplest and most efficient solution by far is to just use one vector:
function vec = ols2(..)
vec = [1,2,..];
end

R2015a

### Community Treasure Hunt

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

Start Hunting!

Translated by