MATLAB: How to align pos/neg numbers with fprintf

alignmentformattingfprintf

I'm trying to recreate the a specific file format (K file), that looks as follows
219 8.0199807e-001 -2.2447408e-002 4.5720000e-002
220 8.0199807e-001 -2.2447408e-002 5.0800000e-002
221 8.0199807e-001 2.3252592e-002 2.2204460e-016
My code now can assemble the matrix correctly, but I'm having trouble aligning positive value numbers with negative ones. For instance, the code above shows up as:
219 1.8290000e+00 -2.7420000e-02 1.0160000e-03
220 1.8290000e+00 -2.7420000e-02 5.0800000e-03
221 1.8290000e+00 9.1400002e-03 -3.5560000e-02
The value in the 3rd row and column is left adjusted which is a huge hassle later on. I can't simply add a "+".
What can I do to properly align them?
The format code I have now for the fprintf command to write them is:
formatspec = ('\t %4i %9.7e %9.7e %9.7e \n');
Any help is greatly appreciated!

Best Answer

Probably the easiest way is to precede each width specifier with a space.
Example:
x = [pi; -pi]
s1 = sprintf('% .4f\n', x)
Another option is to force the sign to be printed:
x = [pi; -pi]
s2 = sprintf('%+.4f\n', x)
producing respectively:
s1 =
3.1416
-3.1416
s2 =
+3.1416
-3.1416
Note that ‘sprintf’ and ‘fprintf’ are essentially the same, except for the nature of the output. I chose ‘sprintf’ to illustrate the concept.