Store all matrices of "for" loop to a file

조회 수: 1 (최근 30일)
Thuy Tran
Thuy Tran 2020년 6월 4일
댓글: Ameer Hamza 2020년 6월 5일
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

채택된 답변

Ameer Hamza
Ameer Hamza 2020년 6월 4일
편집: Ameer Hamza 2020년 6월 4일
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
Thuy Tran
Thuy Tran 2020년 6월 4일
Thanks a lot! It really helpful to me. When I have R2019a or later, I will try the second way.
Ameer Hamza
Ameer Hamza 2020년 6월 5일
I am glad to be of help!

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by