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 个评论
回答(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 中查找有关 Numeric Types 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!