Write text and numbers using fprintf
조회 수: 7 (최근 30일)
이전 댓글 표시
clear all; na = ['a' 'b' 'c']'
cor = [1.67 2.34 3.55]'
cor2 = num2str(cor)
mat = [na cor2]
fileID = fopen('mattest.txt','w');
fprintf(fileID,'%4c %4c \r\n',mat(:,1:2).');
fclose(fileID);
%
Hello all,
From the above script, I would like a textfile
a 1.67
b 2.34
c 3.55
However, cor2 has four columns, so what I get is simply
a 1
b 2
c 3
how can I collapse cor2 into a [3,1] matrix?
Best, J
댓글 수: 1
답변 (1개)
Jan
2017년 10월 30일
na = ['a' 'b' 'c']'; % Now this is a [3 x 1] matrix already
cor = [1.67 2.34 3.55]' % This is a [3 x 1] matrix also
% cor2 = num2str(cor) % Bad idea
% mat = [na cor2] % Wrong idea, they have different types.
fileID = fopen('mattest.txt','w');
for k = 1:numel(na)
fprintf(fileID, '%4c %4f\r\n', na(k), cor(k));
end
fclose(fileID);
Or work with a cell array:
c = cat(2, num2cell(na), num2cell(cor)).';
fileID = fopen('mattest.txt','w');
fprintf(fileID, '%4c %4f\r\n', c{:});
fclose(fileID);
Perhaps you do not want the numerical format %4f, then look in the docs of:
doc fprintf
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Low-Level File I/O에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!