Write text and numbers using fprintf
7 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
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 comentario
Respuestas (1)
Jan
el 30 de Oct. de 2017
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 comentarios
Ver también
Categorías
Más información sobre Low-Level File I/O en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!