Reputation: 241
I want to write three different matrices to a file by using the following code.
REF=[0 6;
1 6;
2 6;
5 6;
10 6;
50 6;
100 6;
1000 6];
dlmwrite('exp.txt',REF,'delimiter','\t','precision',4)
A1=[0 6;
1 3;
2 4;
5 4;
10 4;
50 4;
100 4;
1000 4];
dlmwrite('exp.txt',A1,'delimiter','\t','precision',4)
A2=[0 8;
1 8;
2 8;
5 8;
10 8;
50 8;
100 8;
1000 8];
dlmwrite('exp.txt',A2,'delimiter','\t','precision',4)
fclose(fileID);
But when I run my program, only the last matrix exists in the file, all previous data has been over written. How can I write multiple matrices to a single file without being over written?
Upvotes: 1
Views: 1341
Reputation: 973
Use -append
:
REF=[0 6;
1 6;
2 6;
5 6;
10 6;
50 6;
100 6;
1000 6];
dlmwrite('exp.txt',REF,'delimiter','\t','precision',4)
A1=[0 6;
1 3;
2 4;
5 4;
10 4;
50 4;
100 4;
1000 4];
dlmwrite('exp.txt',A1,'delimiter','\t','precision',4, '-append','roffset',1)
A2=[0 8;
1 8;
2 8;
5 8;
10 8;
50 8;
100 8;
1000 8];
dlmwrite('exp.txt',A2,'delimiter','\t','precision',4, '-append','roffset',1)
Result:
0 6
1 6
2 6
5 6
10 6
50 6
100 6
1000 6
0 6
1 3
2 4
5 4
10 4
50 4
100 4
1000 4
0 8
1 8
2 8
5 8
10 8
50 8
100 8
1000 8
P.S.
You can also use fprintf to have the names of your matrices:
Code:
fileID = fopen('exp.txt','w');
REF=[0 6;
1 6;
2 6;
5 6;
10 6;
50 6;
100 6;
1000 6];
A1=[0 6;
1 3;
2 4;
5 4;
10 4;
50 4;
100 4;
1000 4];
A2=[0 8;
1 8;
2 8;
5 8;
10 8;
50 8;
100 8;
1000 8];
fprintf(fileID,'%s\n','REF = ');
fprintf(fileID,'%d %d\n', REF);
fprintf(fileID,'\n%s\n','A1 = ');
fprintf(fileID,'%d %d\n', A1);
fprintf(fileID,'\n%s\n','A2 = ');
fprintf(fileID,'%d %d\n', A2);
fclose(fileID);
Result:
REF =
0 1
2 5
10 50
100 1000
6 6
6 6
6 6
6 6
A1 =
0 1
2 5
10 50
100 1000
6 3
4 4
4 4
4 4
A2 =
0 1
2 5
10 50
100 1000
8 8
8 8
8 8
8 8
P.S.2
save('mydata.mat','REF', 'A1', 'A2');
then
load('mydata.mat');
Upvotes: 4