简体   繁体   中英

In Matlab, how to specify number of digits in the exponent using formatSpec formatting operator?

I'm writing data to an output text file using the fprintf command in Matlab. How to write a number to the output file, for instance, 1.12345678e-001 , with three digits in the exponent ?

formatSpec = '%1.8e\n';

gives 1.12345678e-01 , not the desired result!

There's a similar question here https://se.mathworks.com/matlabcentral/answers/100772-how-do-i-use-fprintf-to-write-numbers-in-exponential-notation-of-variable-exponent-digits-on-a-windo

But following the instructions given there didn't solve the problem!

You can use this non-regex method:

num = 0.112345678
pow = floor(log10(abs(num)));
sprintf('%.8fe%+.3d', num/10^pow, pow)

ans =
1.12345678e-001

For multiple inputs use this:

num= [.123 .456 .789];
pow = floor(log10(abs(num)));
sprintf('%.8fe%+.3d ', [num./10.^pow; pow])

Not sure if this falls under the category of solution or work-around , but here it goes:

x = .123e25; % example number
formatSpec = '%1.8e\n'; % format specification
s = sprintf(formatSpec, x); % "normal" sprintf
pat = '(?<=e)[+-]\d+'; % regex pattern to detect exponent
s = regexprep(s, pat, sprintf('%+04i', str2double(regexp(s, pat ,'match')))); % zero-pad

It uses regular expressions to identify the exponent substring and replace it with the exponent zero-padded to three digits. Positive exponents include a plus sign, as with fprintf .

This isn't the cleanest answer but you could do something like this. Basic steps are write as is, get the exponent with a regexp, re-write that portion, and replace.

formatSpec = '%1.8e'

tempStr = sprintf(formatSpec,1.12345678e-1);
oldExp  = regexp(tempStr,'e[+-]([0-9]+)$','tokens');
newExp  = num2str(str2double(oldExp{1}{1}),'%03d');
fixedStr = regexprep(tempStr,[oldExp{1}{1} '$'],newExp)

This outputs:

fixedStr =    
1.12345678e-001

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM