Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

To resolve issues starting MATLAB on Mac OS X 10.10 (Yosemite) visit: http://www.mathworks.com/matlabcentral/answers/159016

How to right-justify columns in txt file using fprintf

Asked by JoE on 4 Oct 2013
Latest activity Edited by Cedric Wannaz on 4 Oct 2013

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

JoE

Products

No products are associated with this question.

1 Answer

Answer by Cedric Wannaz on 4 Oct 2013
Edited by Cedric Wannaz on 4 Oct 2013
Accepted answer

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

Cedric Wannaz

Contact us