dlmwrite problem
조회 수: 13 (최근 30일)
이전 댓글 표시
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
댓글 수: 0
채택된 답변
Jan
2011년 11월 21일
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.
댓글 수: 0
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Text Files에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!