How to print in a text file?

36 visualizaciones (últimos 30 días)
Ashesh Choudhury
Ashesh Choudhury el 20 de Oct. de 2020
Comentada: Ameer Hamza el 29 de Oct. de 2020
I have to matrices x=[1;2;3] and U=[1 2 3; 4 5 6; 7 8 9].
I want to generate a .txt file of the name "output.txt" which would contain the following:
"
This is the output
x
1
2
3
U
1 2 3
4 5 6
7 8 9
"
How to do it?

Respuesta aceptada

Ameer Hamza
Ameer Hamza el 20 de Oct. de 2020
A slightly unusual way but it works
x=[1;2;3];
U=[1 2 3; 4 5 6; 7 8 9];
f = fopen('data.txt', 'w');
fprintf(f, 'This is the output\n');
fprintf(f, 'x\n');
writematrix(x, 'data.txt', 'WriteMode', 'append');
fseek(f, 0, 1);
fprintf(f, 'U\n');
writematrix(U, 'data.txt', 'WriteMode', 'append');
fclose(f);
  7 comentarios
Ashesh Choudhury
Ashesh Choudhury el 27 de Oct. de 2020
Is there any way to control the number of digits after decimal that is being printed by writematrix?
Ameer Hamza
Ameer Hamza el 29 de Oct. de 2020
Not possible using writematrix, but you can use fprintf()
x=[1;2;3];
U=[1 2 3; 4 5 6; 7 8 9];
f = fopen('data.txt', 'w');
fprintf(f, 'This is the output\n');
fprintf(f, 'x\n');
fprintf(f, [repmat('%.2f', 1, size(x,2)) '\n'], x);
fprintf(f, 'U\n');
fprintf(f, [repmat('%.2f,', 1, size(U,2)) '\n'], U);
fclose(f);

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Characters and Strings en Help Center y File Exchange.

Etiquetas

Productos


Versión

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by