Search code examples
matlabnumber-formatting

Matlab ShortEng number format via sprintf() and fprintf()?


I like using MATLAB's shortEng notation in the interactive Command Window:

>> a = 123e-12;
>> disp(a);

   1.2300e-10       % Scientific notation. Urgh!

>> format shortEng;
>> disp(a);

   123.0000e-012    % Engineering notation! :-D

But I want to use fprintf:

>> format shortEng;
>> fprintf('%0.3e', a); 
1.2300e-10          % Scientific. Urgh!

How do I print values with fprintf or sprintf with Engineering formatting using the MATLAB Format Operators?

I know I could write my own function to format the values into strings, but I'm looking for something already built into MATLAB.

NOTE: "Engineering" notation differs from "Scientific" in that the exponent is always a multiple of 3.

>> fprintf('%0.3e', a);    % This is Scientific notation.
1.230000e-10

Solution

  • 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.