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 (최근 30일)
이전 댓글 표시
n=20;
x=[1 2 3]
for i=1:n
[y1,y2]=adaptive (x)
end
y=[ 1 2 3; 4 5 6]
댓글 수: 0
채택된 답변
dpb
2021년 10월 23일
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.
댓글 수: 0
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Matrix Indexing에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!