I have a function (ex. adaptive) in a for loop which has two arrays as output. I want to save all the outputs in a single matrix. it can just save the last vector

2 views (last 30 days)
n=20;
x=[1 2 3]
for i=1:n
[y1,y2]=adaptive (x)
end
y=[ 1 2 3; 4 5 6]

Accepted Answer

dpb
dpb on 23 Oct 2021
You have to index the out arrays on the LHS of the assignment or MATLAB will, as you've observed, overwrite the whole variable on assignment with the content of the RHS.
for i=1:n
[y1(i,:),y2(i,:)]=adaptive (x)
end
The above does a bad thing in that y1, y2 are not preallocated so each pass through the loop will dynamically reallocate the resulting arrays. This won't show up with small n and x, but as array sizes grow it can become a real performance bottleneck.
It isn't at all clear what your function adaptive actually returns -- what you have written as the assignment and described in the Q? title (BTW, in future use the body of the Question to ask the Q?, use the title as just a leading headline) aren't consistent.
You've shown two separate variables there, but your last y that one presumes is what you intended as a hint for what you want the output to be is only one variable, it just has two rows.
Show us the content of the function where and how it defines its inputs/outputs.
In general, also, one would instead vectorize the function itself to return array output(s) and pass in the needed arguments including how to determine the output size if it isn't obvious and can be variable rather than calling it in a loop.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!