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
0 个评论
回答(1 个)
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}
另请参阅
类别
在 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!