How Store a set of Matrices independently after each iteration is done in a for loop.

조회 수: 3 (최근 30일)
Hello Matlab again, I am going to ask my question more accurately this time. I am trying to modify an existing code to where I have a set of matrices saved independently after each iteration is complete. The Matrix that I need to be saved each time is 3D ( MN(:,:,14680). it has 14680 of (5*5) matrices stacked up in it. So basically if my outside loop iterates for 5 times, I need to get 5 MN matrices as output saved (MN1, MN2, MN3,MN4, and MN5). I attached a more simplified version of my code ( I tried using "cat" but did not work correctly
)
function [MNPr1,MSA1,MSA1Trans] = Prb_Trans_CR7(X, Lam,Y,UnitArea,n,m)
Xv=X for k=1:2;
X(:,2)=X(:,2)+k; %Incrementally increase all values in X(:,2) by 1
[Mtest,MN, MN1, MN2, MN3, Mtest1, Mtest2] = Predict_all( X,Lam,Y)
[ MS1, MS2,MS3,MSA1,MSA2, MSA3, MSA ] = MatrixCountnew(Mtest1,Mtest2, MN1, MN2, MN3,Y,UnitArea,n)
MNPr1= cat(4,MN1) %For every iteration, I must have one MNPr1 that has MN1 matrix stored in it
MSA1Trans(k)=cat(4,MSA1); % Stores all the MSA1 matrices after each iteration.
X=Xv;% Must reset the values of X(:,2) to original X(:,2) before next iteration starts.
end

답변 (1개)

Jos (10584)
Jos (10584) 2016년 10월 5일
Do not create names like MN1, MN2 etc. What if you have a 1000 matrices likes this? They are all related,, but have different variable names which makes coding very hard ...
If each output is a 3D matrix of the same size, you can stack them in a 4D matrix.
for k=1:5,
MN(:,:,:,k) = rand(2,3,4) ;
end
To access an individual matrix:
CurrentMN = MN(:,:,:,3)
If they are not of the same size, or if you do not want to deal with 4 dimensions, you can try a structure or cell array
for k=1:5,
MNstruct(k).values = rand(2,3,2*k) ;
MNcell{k} = rand(2,4,k+1) ;
end
To access an individual matrix:
MNstruct(2).values
MNcell{4}
  댓글 수: 1
Amine Ben Ayara
Amine Ben Ayara 2016년 10월 5일
Hello Jos, and thank you so much for taking the time to answer. Very helpful input you gave me. So I get how to store matrices within a 4D matrix, but how and where do you think in my code I should make the modification in order to store a set of MN every time an iteration happens. For example, 5 iterations ( i=1:5; the Final 4D matrix should contain 5 sets of MN so I have a specific MN as an output by the end of each loop. Do I make any sense? haha Thank you so much

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by