simoet
simoet

Reputation: 143

Reading and Writing Header to File using MATLAB

I am reading in a .txt-file using importdata:

MC_file = importdata('D:\Simon\Dropbox\SGM\Gigerwald\Results\Multi_SGM_10000.txt');
Data = MC_file.data
Header = MC_file.colheaders

which gives me a struct-variable with the header and the data-body:

data = 10000x52 double
colheaders = 1x52 cell

Now i'd like to change the data, i.e. add some columns to the end of the file and then print the file again with the same header + 5 new columns.

The body can be printed easily using dlmwrite(), e.g. like this:

dlmwrite('SGM.txt',Data,'precision',8,'delimiter','\t','newline','pc','-append')

...but how do I print the header into the file, of which I have a array of cells? I've seen this, but since I end up with 57 columns hard-coding is not an option...

Upvotes: 1

Views: 98

Answers (1)

Dev-iL
Dev-iL

Reputation: 24179

The solution is attainable using repmat. Assuming that your file is tab separated, you can use:

NUM_COLS = 57;

A=cellstr(num2str((1:NUM_COLS)'))';
fid=fopen('newfile.txt','w');

fprintf(fid,repmat('%s\t ',[1,NUM_COLS]),A{:});
fclose(fid);

The result can be previewed with:

sprintf(repmat('%s\t ',[1,NUM_COLS]),A{:})

Upvotes: 2

Related Questions