MATLAB: Store all matrices of “for” loop to a file

for loopoutput file

Dear all,
I have problem of output data "T" (5×4 matrix) of "for loop" to a file, e.g., cvs format. I know that "csvwrite('Data.csv',T)" in the following code is only output the final value of T. I would like to store all "T" matrices in one file. Hope to receive your guilding. Thanks a lot!
A =[ 0 2 6 4 5 2 1
2 0 0 0 0 0 1
0 0 2 1 0 0 1
0 0 0 0 1 1 0];
b = [5.8; 2.4; 1.6; 0.2];
% select 4 columns from 7 columns
colsets = nchoosek(1:7,4);
nCombinations = size(colsets,1) % number of combinations
for i = 1:nCombinations
a = A(:,colsets(i,:));
if rank(a) >= 4
x = a \ b;
if (x(:,:)>=0) & (x(:,:)~=Inf)
T = [a;x'] % 5×4 matrix
csvwrite('Data.csv',T);
end
end
end

Best Answer

Try this
A =[ 0 2 6 4 5 2 1
2 0 0 0 0 0 1
0 0 2 1 0 0 1
0 0 0 0 1 1 0];
b = [5.8; 2.4; 1.6; 0.2];
% select 4 columns from 7 columns

colsets = nchoosek(1:7,4);
nCombinations = size(colsets,1) % number of combinations

T = [];
for i = 1:nCombinations
a = A(:,colsets(i,:));
if rank(a) >= 4
x = a \ b;
if (x(:,:)>=0) & (x(:,:)~=Inf)
T = [T;a;x'] % 5x4 matrix

end
end
end
csvwrite('Data.csv',T);
Alternatively, if you have R2019a or later
A =[ 0 2 6 4 5 2 1
2 0 0 0 0 0 1
0 0 2 1 0 0 1
0 0 0 0 1 1 0];
b = [5.8; 2.4; 1.6; 0.2];
% select 4 columns from 7 columns
colsets = nchoosek(1:7,4);
nCombinations = size(colsets,1) % number of combinations
for i = 1:nCombinations
a = A(:,colsets(i,:));
if rank(a) >= 4
x = a \ b;
if (x(:,:)>=0) & (x(:,:)~=Inf)
T = [a;x'] % 5x4 matrix
writematrix(T, 'Data.csv', 'WriteMode', 'append');
end
end
end