2
votes

If I have a matrix of dimensions [m n] and I need to import the matrix into a tab delimited .txt file i would use:

dlmwrite(Filename, Data, 'delimiter', '\t');

However, what do I need to do if i require a header above each column in the .txt file? Where I need to define each seperate column which refer to different data sets.

thanks

3
What language is this? (you should tag it accordingly) - jonsca
sorry, language is matlab (2011b). - user1053544

3 Answers

2
votes

Silvado has the right idea. Here's a hack I use from time to time:

outfile = '/path/to/file/output.out';
data = magic(5);
header='feat1,feat2,feat3,feat4,feat5'; 
dlmwrite(outfile,header,'delimiter','');
dlmwrite(outfile,data,'delimiter',',','-append');

The result is a csv file with the headers as the first line. Note the hack is to pass an empty delimiter of '' to dlmwrite along with a precompiled header (you could create this in a loop to automate). If performance is a big concern you may be better off using low-level functions.

1
votes

You probably need to write the column headers first using low-level file IO, e.g. fprintf. Then you can write your matrix in the very same file using the '-append' option to dlmwrite.

1
votes

I prefer the nicely aligned columns produced by save and use dlmwrite just to get the headers right.

outfile = '/path/to/file/output.out';
data = magic(5);
header='feat1  feat2  feat3  feat4  feat5'; 
dlmwrite(outfile, header, 'delimiter', '');
save(outfile, data, '-ascii', '-append');