How to right-justify columns in txt file using fprintf

조회 수: 26 (최근 30일)
JoE
JoE 2013년 10월 4일
편집: Cedric 2013년 10월 4일
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

채택된 답변

Cedric
Cedric 2013년 10월 4일
편집: Cedric 2013년 10월 4일
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개)

카테고리

Help CenterFile Exchange에서 Entering Commands에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by