How to print 1x50 array into a text file

14 visualizaciones (últimos 30 días)
Iman Baz
Iman Baz el 23 de Mayo de 2019
Comentada: Akira Agata el 23 de Mayo de 2019
Hello,
I have 1x50 array A=[0.020 0.600 49.915 0.000 0.100 0.000 30.910 51.340 30.850 .... 0.000]
and want to print them into a text file with the below format.
0.020 0.600 49.915 0.000 0.100 0.000 30.910 51.340
30.850 51.460 13.378 4.600 0.000 0.000 0.000 0.000
0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000
0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000
0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000
0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000
0.000 0.000
How should I do this?
  1 comentario
Jan
Jan el 23 de Mayo de 2019
Editada: Jan el 23 de Mayo de 2019
And what exactly is the "below format"? Do you want spaces or tab stops between the numbers? Tab stops before the line breaks? A fixed number of 8 columns, or does this depend on the number of elements? A trailing linebreak or not? 10 characters per number and 3 digits after the point? Please mention the details.

Iniciar sesión para comentar.

Respuesta aceptada

Jan
Jan el 23 de Mayo de 2019
Maybe:
[fid, msg] = fopen(FileName, 'w');
assert(fid ~= -1, 'Cannot open file for writing: %s\n%s\n', FileName, msg);
fmt = [repmat('%10.3f', 1, 8), '\n'];
fprintf(fid, fmt, A.');
fclose(fid);

Más respuestas (2)

Akira Agata
Akira Agata el 23 de Mayo de 2019
How about the following?
dlmwrite('output.txt',reshape(A(1:48),8,6)','delimiter','\t');
dlmwrite('output.txt',A(49:50),'-append','delimiter','\t');
  2 comentarios
Iman Baz
Iman Baz el 23 de Mayo de 2019
Dear Agata,
Thank you for your prompt reply. that's worked.
but I need numbers in format %10.3f.
Akira Agata
Akira Agata el 23 de Mayo de 2019
Dear Hossein-san,
Thank you for your comment.
Sorry, I've missed your 'fprintf' tag in your original post.
Just FYI, your can save as %10.3f format by dlmwrite function, too, by:
dlmwrite('output.txt',reshape(A(1:48),8,6)','delimiter','\t','precision','%10.3f');
dlmwrite('output.txt',A(49:50),'-append','delimiter','\t','precision','%10.3f');

Iniciar sesión para comentar.


Raj
Raj el 23 de Mayo de 2019
Editada: Raj el 23 de Mayo de 2019
Answer given by Akira is the optimal solution but since you have mentioned 'fprintf' as a tag, here are two ways to get what you want using 'fprintf'
fid=fopen('MyFile.txt','w'); % Open text file
fprintf(fid, '%10.3f %10.3f %10.3f %10.3f %10.3f %10.3f %10.3f %10.3f\r\n',A); % Write 8 elements in each line from A with 3 digits after decimal
fclose(fid); % Close the file
or an even weird way:
fid=fopen('MyFile.txt','w');
for i=1:numel(A)
if rem(i,8)~=0
fprintf(fid, ' %10.3f',A(1,i));
else
fprintf(fid, ' %10.3f\r\n',A(1,i));
end
end
fclose(fid);
Good luck!!

Categorías

Más información sobre Language Support en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by