Multiple Outputs of a function into a single vector
38 views (last 30 days)
Show older comments
I am a new Matlab programmer, and am familiar with functional languages such as python. In my university Matlab course, we are required to write test functions similar to this one:
function [x,y] = f(a, b)
x = a;
y = b;
end
This function is called with a number of different parameters, and I'd like to store them in one large array. Previous answers I've found lead me to this solution:
returns = zeros(4, 2);
[returns(0,0), returns(0,1)] = f(a0, b0);
[returns(1,0), returns(1,1)] = f(a1, b1);
[returns(2,0), returns(2,1)] = f(a2, b2);
[returns(3,0), returns(3,1)] = f(a3, b3);
but when "returns" has more than two outputs, this gets ugly very fast. The only other solution I've found instead breaks this into two lines:
returns = zeros(4, 2);
[A, B] = f(a0, b0);
returns(0, :) = [A, B];
[A, B] = f(a1, b1);
returns(1, :) = [A, B];
[A, B] = f(a2, b2);
returns(2, :) = [A, B];
[A, B] = f(a3, b3);
returns(3, :) = [A, B];
But if I merge those two lines, it broadcasts A into every element of the vector. In Python, I could re-cast the output as a numpy array with almost identical syntax. Is there a similar function in Matlab? Every output has the same data type. I'm aware this can be solved with for loops, but I'm interested if a functional solution exists.
0 Comments
Accepted Answer
Walter Roberson
on 20 Sep 2022
There is no functional solution in MATLAB. The only way to capture multiple outputs is an assignement statement. The assignment can be to an expansion such as
[returns{1:5}] = f(a3, b3)
but you cannot gather the outputs "in-line" like
min({f{a3,b3)}) %will not work to capture multiple outputs
More Answers (1)
James Tursa
on 20 Sep 2022
You could modify f( ) to return a vector. Or if you didn't want to modify f( ) you could create a helper function that does this. E.g.,
function v = f2(a,b)
[A,B] = f(a,b);
v = [A,B];
end
Then just call f2( ) instead of f( ).
Another approach is to have the helper function use the nargout/varargout feature to detect how many outputs are requested by the caller. E.g.,
function varargout = f2(a,b)
[A,B] = f(a,b);
if nargout == 2
varargout{1} = A;
varargout{2} = B;
else
varargout{1} = [A,B];
end
end
See Also
Categories
Find more on Call Python from MATLAB in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!