Blub Bla
Blub Bla

Reputation: 136

Include table header when writing matrix to file

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?

Upvotes: 0

Views: 709

Answers (2)

Blub Bla
Blub Bla

Reputation: 136

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');

Upvotes: 2

Adriaan
Adriaan

Reputation: 18177

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.

Upvotes: 2

Related Questions