Write text and numbers using fprintf

5 次查看(过去 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 中查找有关 Numeric Types 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by