How to right-justify columns in txt file using fprintf
49 views (last 30 days)
Show older comments
Hi guys.
I was trying to find the solutions, but unsuccessfully. Here is my problem.
I want to write vector with these values to .dat file (e.g.):
a = [0.2569; 1.7856; 16.2451; 485.5412; 0.2100]
As you can see, the number of decimal places is the same for every value, but there are differences in integer values.
I get this:
0.2569
1.7856
16.2451
485.5412
0.2100
But I want to get this in the file:
0.2569
1.7856
16.2451
485.5412
0.2100
I know there is no higher value of this vector than 1000, so I used
fprintf ('file.dat','% 8.4f\n',a);
Is there a possibility to align numbers in a column according to decimal point?
Thank you very much for your response.
Joe
0 Comments
Accepted Answer
Cedric
on 4 Oct 2013
Edited: Cedric
on 4 Oct 2013
There shouldn't be a white space in the formatSpec string between the % and the format specifier. Observe the difference on screen between
fprintf('% 8.4f\n', a)
which produces unaligned numbers and
fprintf('%8.4f\n', a)
which aligns them correctly. Also, if you want to write to file, you have to pass a file identifier to FPRINTF and not a file name. Here is one way to do it:
fid = fopen('file.dat', 'w') ; % See doc fopen for other modes.
fprintf(fid, '%8.4f\n', a) ;
fclose(fid) ;
0 Comments
More Answers (0)
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!