Write text and numbers using fprintf

조회 수: 7 (최근 30일)
Jonathan Oekland Torstensen
Jonathan Oekland Torstensen 2017년 10월 30일
답변: Jan 2017년 10월 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
Jan
Jan 2017년 10월 30일
편집: Jan 2017년 10월 30일
"Collapse cor2 into a [3,1] matrix"? You convert 1.67 to a char, so what do you expect? What does "cor2 has four columns" mean?

댓글을 달려면 로그인하십시오.

답변 (1개)

Jan
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

카테고리

Help CenterFile 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!

Translated by