fprintf and fopen changing the data I'm trying to write
조회 수: 6 (최근 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에서 Characters and Strings에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!