save to 2nd decimal, then add brackets

1 次查看(过去 30 天)
I needed to round a matrix of double to the second decimal. And also convert the second row such that each entry is in brackets, and then save to mat, txt, or xls.
This is the initial matrix
A=[1.224, 1.338;
2.451, -2.367;
1.222, 4.123]
For rounding, I tried
sprintf('%.2f\n',A)
But it generates a vector not a matrix. For adding the brackets, I tried to use
strcat('(',A(2,:),')'), not working.
The change should result in this (either a mat or txt or xls)
B=[1.22, 1.34;
(2.45), (-2.37);
1.22, 4.12]

采纳的回答

Stephen23
Stephen23 2018-2-3
编辑:Stephen23 2018-2-3
A = [1.224,1.338;2.451,-2.367;1.222,4.123];
fdir = '.'; directory
name = 'myfile.txt';
fmt = 'B=[%.2f, %.2f;\n(%.2f), (%.2f);\n%.2f, %.2f]';
[fid,msg] = fopen(fullfile(fdir,name),'wt');
assert(fid>=3,msg)
fprintf(fid,fmt,A.');
fclose(fid);
  3 个评论
Stephen23
Stephen23 2018-2-3
The code save a file that produces exactly what you asked for:
B=[1.22, 1.34;
(2.45), (-2.37);
1.22, 4.12]
If you want something else please specify it clearly.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Dates and Time 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by