fprintf and fopen changing the data I'm trying to write

7 views (last 30 days)
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.

Accepted Answer

Star Strider
Star Strider on 14 Apr 2015
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 Comments
Kirby Runyon
Kirby Runyon on 15 Apr 2015
That worked! Thank you. How did you know to do that (you can reply to me directly)? Doing your 2nd trick took care of both problems--the bad data and the 48's.
Star Strider
Star Strider on 15 Apr 2015
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.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!