How can I store a matrix of varying size in each iteration of a for loop?
조회 수: 2 (최근 30일)
이전 댓글 표시
Hi,
I have a function that gives an output of a single column, T, and also a matrix Y. The number of columns of Y remains constant but the number of rows changes depending on the input parameter. The number of rows of T also changes depending on the input parameter.
for rho = 500:100:1000
[T Y]= myFunction(rho)
end
I am varying the parameter rho from 500 to 1000, however want to store each iteration in a separate matrix, as I wish to compare the outputs at different rho values. Currently, although all matrix outputs appear in the command window, I cannot store each iteration for further use, only the last iteration at rho=1000 is accessible. I was wondering how this would be possible? Thank you very much for any help as I am a beginner to Matlab.
An example of the output in the command window for one value of rho inputted:
![Screenshot 2019-08-02 at 14.43.19.png](https://www.mathworks.com/matlabcentral/answers/uploaded_files/232365/Screenshot%202019-08-02%20at%2014.43.19.png)
댓글 수: 0
채택된 답변
Jos (10584)
2019년 8월 2일
Since T and Y are related for a specific value of rho, a struct array is useful here.
rho_range = 500:100:1000 ;
for k = 1:numel(rho_range)
rho = rho_range(k) ;
[data(k).T data(k).Y]= myFunction(rho) ;
end
You might want to pre-allocate the struct array to speed things up. One easy way to do this is to reverse the loop:
for k = numel(rho_range):-1:1
댓글 수: 3
Jos (10584)
2019년 8월 2일
My pleasure. Unfortunately, user madhan ravi deleted his answer, as cell arrays are a good option too.
[T{k}, Y{k}] = myFunction(rho) ;
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!