Clear Filters
Clear Filters

Store all matrices of "for" loop to a file

1 view (last 30 days)
Dear all,
I have problem of output data "T" (5x4 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'] % 5x4 matrix
csvwrite('Data.csv',T);
end
end
end

Accepted Answer

Ameer Hamza
Ameer Hamza on 4 Jun 2020
Edited: Ameer Hamza on 4 Jun 2020
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
  2 Comments
Thuy Tran
Thuy Tran on 4 Jun 2020
Thanks a lot! It really helpful to me. When I have R2019a or later, I will try the second way.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!