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

조회 수: 20 (최근 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일
편집: Stephen23 2025년 8월 26일
[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일
"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일
이동: Torsten 2025년 8월 26일

카테고리

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