Effacer les filtres
Effacer les filtres

How to print in a text file?

26 vues (au cours des 30 derniers jours)
Ashesh Choudhury
Ashesh Choudhury le 20 Oct 2020
Commenté : Ameer Hamza le 29 Oct 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?

Réponse acceptée

Ameer Hamza
Ameer Hamza le 20 Oct 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 commentaires
Ashesh Choudhury
Ashesh Choudhury le 27 Oct 2020
Is there any way to control the number of digits after decimal that is being printed by writematrix?
Ameer Hamza
Ameer Hamza le 29 Oct 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);

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Characters and Strings dans Help Center et File Exchange

Produits


Version

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by