writematrix: how to get formatted txt-output?

조회 수: 11 (최근 30일)
JarryG
JarryG 2024년 9월 24일
댓글: Stephen23 2024년 9월 24일
I have been using "dlmwrite" to get nicely formatted text output:
dlmwrite('file.txt',M,'delimiter',' ','precision','%10.2f');
txt-file looked like:
100.00 0.00 4500.00
0.00 1.00 38.29
1.00 1.00 38.22
As "dlmwrite" is not recommended anymore, I tried to use "writematrix" instead. But it does not have "precision" parameter:
writematrix(round(M,2),'file.txt','Delimiter',' ');
txt-file is not so nicely formatted:
100 0 4500
0 1 38.29
1 1 38.22
That's a problem especially with bigger matrices, as offset between lines is getting bigger and bigger, and I can not recognize columns anymore. Is there any way to fix this?

답변 (3개)

Stephen23
Stephen23 2024년 9월 24일
M = [100,0,4500;0,1,38.29;1,1,38.22]
M = 3×3
1.0e+03 * 0.1000 0 4.5000 0 0.0010 0.0383 0.0010 0.0010 0.0382
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
S = join(compose("%10.2f",M),'');
writelines(S,"test.txt")
Checking:
type test.txt
100.00 0.00 4500.00 0.00 1.00 38.29 1.00 1.00 38.22

Aquatris
Aquatris 2024년 9월 24일
편집: Aquatris 2024년 9월 24일
Use 'tab' delimiter option instead of single space.
M = [100 0 4500;0 1 38.29;1 1 38.22];
writematrix(round(M,2),'file.txt','Delimiter',' ');
type('file.txt')
100 0 4500 0 1 38.29 1 1 38.22
writematrix(round(M,2),'file2.txt','Delimiter','tab');
type('file2.txt')
100 0 4500 0 1 38.29 1 1 38.22

SACHIN KHANDELWAL
SACHIN KHANDELWAL 2024년 9월 24일
Hi,
Seems that you want to use 'precision' as key value pair with 'writematrix'. I think this is currently limitation. I found the following workaround working :
M = magic(5)*pi; % Create a 5x5 matrix of numeric values
s = num2str(M,3); % create a character array that represents the numeric values in "M" with 3 significant digits
T = str2num(s); % convert "s" back into a numeric matrix.
writematrix(T,'myFile.txt','Delimiter',' ');
  댓글 수: 1
Stephen23
Stephen23 2024년 9월 24일
In case anyone is wondering:
M = [100,0,4500;0,1,38.29;1,1,38.22]
M = 3×3
1.0e+03 * 0.1000 0 4.5000 0 0.0010 0.0383 0.0010 0.0010 0.0382
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
s = num2str(M,3); % create a character array that represents the numeric values in "M" with 3 significant digits
T = str2num(s); % convert "s" back into a numeric matrix.
writematrix(T,'myFile.txt','Delimiter',' ');
type myFile.txt
100 0 4500 0 1 38.3 1 1 38.2

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Text Files에 대해 자세히 알아보기

태그

제품


릴리스

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by