Writematrix loses precision with string present in data

9 ビュー (過去 30 日間)
Martin
Martin 2025 年 3 月 18 日
回答済み: Walter Roberson 2025 年 3 月 18 日
I am saving a matrix to file and need full precision in the data. I am using the writematrix function, and my problem can be shown in this minimal example:
writematrix([1;0.123456789],"./testA.txt")
writematrix(["Test";0.123456789],"./testB.txt")
Then testA.txt:
1
0.123456789
And testB.txt
Test
0.12346
Is there a way to have strings (such as a header row) in my matrix but retain the full precision in the data?

採用された回答

Walter Roberson
Walter Roberson 2025 年 3 月 18 日
writematrix(["Test";compose("%.999g", 0.123456789)],"./testB.txt")
dbtype testB.txt
1 Test 2 0.12345678899999999733605449137030518613755702972412109375
Retains full precision.

その他の回答 (1 件)

dpb
dpb 2025 年 3 月 18 日
移動済み: dpb 2025 年 3 月 18 日
["Test";0.123456789]
ans = 2x1 string array
"Test" "0.12346"
The problem, if there is one, is in combining the string and the numeric into one array; MATLAB can have only one data type in an array other than a cell array and so the numeric value was coerced to a string before it was written; ergo, it isn't writematrix that is the issue here, it's trying put a square peg in a round hole; mixing data types inappropriately.
Probably the easiest workaround with the minimal example would to use a table instead...
tT=table(0.123456789,'VariableNames',"Test")
tT = table
Test _______ 0.12346
writetable(tT,"testB.txt",'WriteVariableNames',1)
type testB.txt
Test 0.123456789

カテゴリ

Help Center および File ExchangeText Files についてさらに検索

製品


リリース

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by