MATLAB: Collect conditional matrices from a loop in a 2D or cell array

save array matrix conditional export overwrite

For a project, I need to draw millions of random 3×3 matrices, take the QR composition of them, transpose the Q matrix and multiply it with a given matrix. Of the resulting matrices (C), I need to store all these matrices that fulfill certain conditions (BB) to do statistical analysis with them (I prefer do that with Excel, so I would export the total array to excel).
My question is how to store these BB matrices from a loop without the last one overwriting the previous one. So far, I have:
B =[...
7.797562562, -0.832787948, -1.725054903;...
2.11093262, 3.138528042, -0.326926679;...
2.128339023, -0.061787665, 6.644309749];
for k = 1 : 50;
rd=rand(3);
[Q,R]=qr(rd);
D=Q';
C=B*D;
if C(1,1)>0 && C(2,2)>0 && C(3,3)>0 && C(3,1)<0 && C(3,2)>0,
BB=C;
end
end
Resulting is a collection (less than the amount of loops) of BB matrices, which I want to export. However, where I save them (save test.mat BB), the last BB matrix overwrites the other one and when I use subscripts to define the loop number, I get this error:
??? In an assignment A(I) = B, the number of elements in B and
I must be the same.
Anybody that can help me? I guess it shouldn´t be too difficult, so any answer could help me out!

Best Answer

Sounds like you need a cell array
B =[...
7.797562562, -0.832787948, -1.725054903;...
2.11093262, 3.138528042, -0.326926679;...
2.128339023, -0.061787665, 6.644309749];
numSim = 50;
results = cell(numSim,1);
counter = 1;
for k = 1 : numSim;
rd=rand(3);
[Q,R]=qr(rd);
D=Q';
C=B*D;
if C(1,1)>0 && C(2,2)>0 && C(3,3)>0 && C(3,1)<0 && C(3,2)>0,
results(counter) = {C};
counter = counter + 1;
%BB=C; No longer needed
end
end
results(counter + 1 : end) = [];
%All your results will be in the cell array
And if you need to extract a particular result
BB = results{ii};
Note that you could also save inside the loop, but since C is small, it is probably better this way.