How to assign the multiple outputs of a function to a single vector AVOIDING TO MANUALLY ASSIGN EACH OUTPUT?

39 次查看(过去 30 天)
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()
test = 3×1
1 1 1
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
test2(1:3) = f()
test2 = 1×3
1 1 1
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
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]
outvector = 3×1
1 2 3
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
% or in alternative
[outvector2(1) outvector2(2) outvector2(3)] = f(1)
outvector2 = 1×3
1 2 3
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
outvector2 = 1×3
1 2 3
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
outvector2 = 1×3
1 2 3
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
outvector = outvector(:) % since it has to be a column vector
outvector = 3×1
1 2 3
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
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?

采纳的回答

Stephen23
Stephen23 2025-8-26,19:06
编辑:Stephen23 2025-8-26,19:07
[C{1:3}] = f();
V = [C{:}]
V = 1×3
1 2 3
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
Make sure to preallocate C if it might already exist.
function [out1,out2,out3] = f()
out1 = 1;
out2 = 2;
out3 = 3;
end
  3 个评论
Stephen23
Stephen23 2025-8-27,9:41
"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.

请先登录,再进行评论。

更多回答(1 个)

Torsten
Torsten 2025-8-26,18:47
移动:Torsten 2025-8-26,18:47

类别

Help CenterFile Exchange 中查找有关 Operating on Diagonal Matrices 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by