save to 2nd decimal, then add brackets

조회 수: 3 (최근 30일)
Dave
Dave 2018년 2월 3일
댓글: Stephen23 2018년 2월 3일
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
Dave
Dave 2018년 2월 3일
got it using \t, thanks man
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에서 Characters and Strings에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by