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

I like to use MATLAB 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 to print values โ€‹โ€‹using fprintf or sprintf using PDF formatting using MATLAB Format Operators ?

I know that I can write my own function to format values โ€‹โ€‹in strings, but I'm looking for something already built into MATLAB.

NOTE. The Engineering notation differs from Scientific in that it is always a multiple of 3.

 >> fprintf('%0.3e', a); % This is Scientific notation. 1.230000e-10 
+5
source share
3 answers

It is not possible to use the fprintf format specifier directly for the required format. The method is to use the output of disp as a string for printing. But disp does not return a string, it writes directly to standard output. So how to do this?

Here evalc (eval with capturing 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 workaround, of course, can have unpleasant consequences in many respects due to unverified inputs of auxiliary functions. But this illustrates the point and is one of the rare cases where the offended family of eval functions is virtually indispensable.

+3
source

You can use the following utility:

http://www.people.fas.harvard.edu/~arcrock/lib118/numutil/unpacknum.m

This will unpack the number also in accordance with the given number N and ensures that the indicator is a multiple of N. Assuming N = 3, you have technical designations.

In more detail, unpacknum takes 3 arguments: the number x , the base ( 10 if you want the constructor notation), and the value N ( 3 , if you want the constructor), and returns a pair ( f , e ) that you can use in fprintf()

For a quick example, check out unpacknum help.

+2
source

This function converts a value to a string in the technical notation:

 function sNum = engn(value) exp= floor(log10(abs(value))); if ( (exp < 3) && (exp >=0) ) exp = 0; % Display without exponent else while (mod(exp, 3)) exp= exp - 1; end end frac=value/(10^exp); % Adjust fraction to exponent if (exp == 0) sNum = sprintf('%+8.5G', frac); else sNum = sprintf('%+8.5GE%+.2d', frac, exp); end end 

You can customize the format to your liking. Use in conjunction with fprintf is quite simple:

 fprintf('%s\t%s\n', engn(543210.123), engn(-0.0000567)) % +543.21E+03 -56.7E-06 fprintf('%s\t%s\n', engn(-321.123), engn(876543210)) % -321.12 +876.54E+06 
0
source

Source: https://habr.com/ru/post/1242693/


All Articles