How to write the data to a file with a specific format?
11 views (last 30 days)
Show older comments
Hi,
I want to save my data to a file in the following format: two blank spaces at the beginning of each column, scientific notation with only one place before the dot, six decimals, and four places for the exponent. Please keep in mind that if a number is negative, there should be no number before the dot. This way, I could get a line with constant character length. Any idea how to do it using fprint?
Thanks,
Mohsen
0.000000E+0000 0.125000E+0000 0.125000E+0000 0.000000E+0000
0.250000E+0000 0.125000E+0000 0.125000E+0000 0.149889E+0001
0.500000E+0000 0.125000E+0000 0.125000E+0000 0.200552E+0001
0.750000E+0000 0.125000E+0000 0.125000E+0000 0.107946E+0001
0.100000E+0001 0.125000E+0000 0.125000E+0000 -.340539E+0000
0.125000E+0001 0.125000E+0000 0.125000E+0000 -.259384E+0000
0 Comments
Answers (1)
dpb
on 18 Jan 2023
Edited: dpb
on 19 Jan 2023
>> fmt=[repmat('%14.6E',1,size(X,1)) '\n'];
>> fprintf(fmt,X.')
0.000000E+00 1.250000E-01 1.250000E-01 0.000000E+00 2.500000E-01 1.250000E-01
1.250000E-01 1.498890E+00 5.000000E-01 1.250000E-01 1.250000E-01 2.005520E+00
7.500000E-01 1.250000E-01 1.250000E-01 1.079460E+00 1.000000E+00 1.250000E-01
1.250000E-01 -3.405390E-01 1.250000E+00 1.250000E-01 1.250000E-01 -2.593840E-01
>>
is as close as you can get with fprintf on its own; it doesn't provide the flexibility to set a field width on the exponent field. To do that, you'd have to do string manipulation or "roll your own" output formatter.
NOTA BENE: The field width specifier still produces a fixed-width output record; the minus simply takes up the implied plus of non-negative values.
I forget if C-standard includes the scale factor to force the leading zero form or not; one can do that with Fortran FORMAT, but C formatting string notation isn't nearly as user-convenient nor powerful as FORMAT syntax. It's unfortunate Mathworks took the easy way out when converted from original FORTRAN to C and didn't keep the Fortran FORMATted i/o. Fixed-width files wouldn't have been broken for almost 30 years before the final introduction of the fixed-width import object in that case...
0 Comments
See Also
Categories
Find more on Low-Level File I/O in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!