Matlab ShortEng number format via sprintf() and fprintf()?
There is no way to use directly fprintf
format specifier for the format you require. A way around is to use the output of disp
as a string to be printed. But disp
doesn't return a string, it writes directly to the standard output. So, how to do this?
Here's where evalc
(eval with capture of output) comes to the rescue:
%// Create helper function
sdisp = @(x) strtrim(evalc(sprintf('disp(%g)', x)));
%// Test helper function
format ShortEng;
a = 123e-12;
fprintf(1, 'Test: %s', sdisp(a));
This is a workaround, of course, and can backfire in multiple ways because of the untested inputs of the helper functions. But it illustrates a point, and is one of the rare occasions where the reviled eval
function family is actually irreplaceable.
You can use the following utility:
http://www.people.fas.harvard.edu/~arcrock/lib118/numutil/unpacknum.m
This will unpack the number also according to a given number N and makes sure that the exponent will be a multiple of N. By putting N=3 you have the Engineering Notation.
More into detail, unpacknum
takes 3 arguments: the number x
, the base (10
if you want Engineering Notation) and the value N (3
if you want Engineering Notation) and it returns the couple (f
,e
) which you can use in fprintf()
.
Check the unpacknum
help for a quick example.