我想使用以下代码将三个不同的矩阵写入文件。
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);
但是当我运行我的程序时,文件中只存在最后一个矩阵,所有以前的数据都已被覆盖。如何在不被覆盖的情况下将多个矩阵写入单个文件?
答案 0 :(得分:4)
使用-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)
结果:
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。强>
您还可以使用fprintf来获取矩阵的名称:
代码:
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);
结果:
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');
然后
load('mydata.mat');