fprintf and fopen changing the data I'm trying to write
5 ビュー (過去 30 日間)
古いコメントを表示
I'm trying to save the result of calculations as an ASCII using fopen and fprintf, but my data becomes corrupted. Snippet below, where the variables are vectors calculated above inside a for loop:
fid01=fopen('Specific_Momentum_and_KE.txt', 'a+');
fprintf(fid01, '%.4f, %.4f, %.4f, %.4f\r\n',tstep, xfland, mag_land_vel, mag_land_KE);
fclose(fid01);
end
I'm getting seemingly random strings of integers in my file, and the numbers which are supposed to be there are wrong--they don't match the output from my Matlab script. Example from the ASCII:
48.0000, 48.0000, 48.0000, 48.0000
0.5053, 0.5862, 0.5963, 0.5923
0.5722, 0.6441, 0.6507, 0.5837
0.6534, 0.6464, 0.6737, 0.6606
0.6153, 0.6864, 0.6746, 0.6344
0.6978, 0.7149, 0.7490, 0.6757
Where the heck did those 48's come from?? Also, the second column should be
0.5052
0.5862
0.5962
0.5922
0.5721
but it's like Matlab is changing my data! Very bad deal. Please help.
0 件のコメント
採用された回答
Star Strider
2015 年 4 月 14 日
The ‘48’ are ASCII representations of the string representation of zero. The first row of your array must be a vector of character ‘0’ rather than numeric ‘0’.
q = char(48)
q2 = uint8(['0' 'O'])
5 件のコメント
Star Strider
2015 年 4 月 15 日
My pleasure!
I knew how to do it from having worked with MATLAB for a while, and having encountered that problem myself. The documentation for fprintf is confusing (at least to me):
- fprintf(fileID,formatSpec,A1,...,An) applies the formatSpec to all elements of arrays A1,...An in column order, and writes the data to a text file. fprintf uses the encoding scheme specified in the call to fopen.
In the example that accompanies that part of the documentation, the data are in row vectors. This is in contrast to the usual column-major representation in MATLAB.
So if your data are in columns rather than rows, you have to transpose it to write it correctly. Concatenating them all into a single matrix first, then transposing it, is the easiest and most efficient way to use fprintf (and sprintf) to write data.
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Text Data Preparation についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!