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!
formatSpec — Format of output fields. formatting operators. Format of the output fields, specified using formatting operators. formatSpec also can include ordinary text and special characters. If formatSpec includes literal text representing escape characters, such as \n , then sprintf translates the escape characters.
For example, %f converts floating-point values to text using fixed-point notation. Adjust the format by adding information to the operator, such as %. 2f to represent two digits after the decimal mark, or %12f to represent 12 characters in the output, padding with spaces as needed.
By default, MATLAB® uses 16 digits of precision. For higher precision, use the vpa function in Symbolic Math Toolbox™. vpa provides variable precision which can be increased without limit. When you choose variable-precision arithmetic, by default, vpa uses 32 significant decimal digits of precision.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With