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()
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 个评论
采纳的回答
Stephen23
2025-8-26,19:06
编辑:Stephen23
2025-8-26,19:07
[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 个评论
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.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Operating on Diagonal Matrices 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!