How to assign the multiple outputs of a function to a single vector AVOIDING TO MANUALLY ASSIGN EACH OUTPUT?
8 views (last 30 days)
Show older comments
Hello
I have a function returning as output 10 1x1 double values
I can't rewrite the function to provide the output as a vector
As you can understand it is quite burdersone to assign each of them individually any time so i would like to assign them to a vector and work on it with a cycle
the problem is that a sintax like the following
output_matrix(:,1) = function(input)
applyes the arithmetic expansion to the output matrix so the first column of my matrix doesn't become the full otuput of the function but silply fills it with copies of the first output value of the function
how can i do this without individually calling out 10 variables for each time i will have to call this function for the rest of my life?
An example of my problem is:
function [out1 out2 out3] = f(~)
out1 = 1;
out2 = 2;
out3 = 3;
end
test = zeros(3,1);
test(:) = f()
test2(1:3) = f()
As you can see neither of them is working, limiting to copy the first output 3 times
I know one solution to this is
[test1 test2 test3] = f();
outvector = [test1; test2; test3]
% or in alternative
[outvector2(1) outvector2(2) outvector2(3)] = f(1)
outvector = outvector(:) % since it has to be a column vector
But doing this actually means calling 10 variables individually each time i call the function and it pollutes a lot the code, plus is burdensome, since it has to go in a cycle and the output vector has to become a matrix
So... can I do it is some other way?
0 Comments
Accepted Answer
Stephen23
on 26 Aug 2025
Edited: Stephen23
on 26 Aug 2025
[C{1:3}] = f();
V = [C{:}]
Make sure to preallocate C if it might already exist.
function [out1,out2,out3] = f()
out1 = 1;
out2 = 2;
out3 = 3;
end
3 Comments
Stephen23
on 27 Aug 2025
"but used C{1:3} = f() instead of [C{1:3}] = f()"
Multiple output arguments require square brackets:
Using a comma-separated list on the LHS does not change the need to use square brackets.
See Also
Categories
Find more on Operating on Diagonal Matrices in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!