问题
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