Borrar filtros
Borrar filtros

dlmwrite problem

5 visualizaciones (últimos 30 días)
ricco
ricco el 21 de Nov. de 2011
Can someone help put the final touches to the following code. Im attempting to create a .txt file which has a first row specified by 'header' and then attempting to add 'data' from the second row onwards, 'feat1' should be placed above the first column of 'data' and so on. So far I have attempted to import 'header' first and then use append to import 'data'
clear all
outfile= '/path/to/file/output.txt';
data = magic(5);
header={'feat1','feat2','feat3','feat4','feat5'};
dlmwrite(outfile,header,'delimiter','');
dlmwrite(outfile,data,'delimiter','\t','-append');
This doesnt work as all of 'header' appears in the first column and by typing '\t' to try and make it tab delimited it inputs a tab between each letter.
I also tried to wirte a loop for importing 'header':
outfile= '/path/to/file/output.txt';
data = magic(5);
header={'feat1','feat2','feat3','feat4','feat5'};
for i=1:5;
dlmwrite(outfile,header{1,i},'delimiter','');
end
dlmwrite(outfile,data,'delimiter','\t','-append');
This doesn't work as it only stores 'feat5' in the .txt file.
Any advice?
cheers

Respuesta aceptada

Jan
Jan el 21 de Nov. de 2011
See help dlmwrite: This function is though to export matrices, but not cell strings. You can use fprintf instead fpr the header:
outfile = '/path/to/file/output.txt';
header={'feat1','feat2','feat3','feat4','feat5'};
data = magic(5);
fid = fopen(outfile, 'w');
if fid == -1; error('Cannot open file: %s', outfile); end
fprintf(fid, '%s\t', header{:});
fprintf(fid, '\n');
fclose(fid);
dlmwrite(outfile,data,'delimiter','\t','-append');
BTW. you can use fprintf directly for the data also instead of dlmwrite:
Fmt = [repmat('%g\t', size(data, 2)), '\n'];
fprintf(fid, Fmt, transpose(data));
fclose(fid);
This is faster than closing the file and re-opening it for appending through dlmwrite.

Más respuestas (0)

Categorías

Más información sobre Data Import and Export en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by