How to print in a text file?

42 views (last 30 days)
Ashesh Choudhury
Ashesh Choudhury on 20 Oct 2020
Commented: Ameer Hamza on 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?

Accepted Answer

Ameer Hamza
Ameer Hamza on 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 Comments
Ashesh Choudhury
Ashesh Choudhury on 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 on 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);

Sign in to comment.

More Answers (0)

Categories

Find more on Characters and Strings in Help Center and File Exchange

Products


Release

R2020a

Community Treasure Hunt

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

Start Hunting!