Include table header when writing matrix to file

ぃ、小莉子 提交于 2019-12-23 04:47:11

问题


I write a matrix from Matlab to a file using dlmwrite:

A = [1,2,3; 
     4,5,6; 
     7,8,9];

dlmwrite('output.txt', A, 'delimiter','\t');

This gives me this output.txt:

1         2         3
4         5         6
7         8         9

Now I would like to add a header to have the following result:

columnA   columnB   columnC
1         2         3
4         5         6
7         8         9

How can I achieve that?


回答1:


Headers = ['columnA',   'columnB',   'columnC'];
dlmwrite('output.txt', Headers, 'delimiter','\t');
A = [1,2,3; 4,5,6; 7,8,9];
dlmwrite('output.txt', A, 'delimiter','\t','-append');

using the argument '-append' makes dlmwrite stick everything at the end of the existing file. This way the first dlmwrite writes a header in the file, the second dlmwrite writes the matrix below the header in the same file.




回答2:


Building upon A. Visser's answer, I found the following solution:

A = [1,2,3; 4,5,6; 7,8,9];
out = fopen('output.txt','w');
fprintf(out,['ColumnA', '\t', 'ColumnB', '\t', 'ColumnC', '\n']);
fclose(out);
dlmwrite('output.txt', A, 'delimiter','\t','-append');


来源:https://stackoverflow.com/questions/32091926/include-table-header-when-writing-matrix-to-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!