How to print in a text file?

26 次查看(过去 30 天)
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?

采纳的回答

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

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Characters and Strings 的更多信息

产品


版本

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by