简体   繁体   English

在Matlab中,如何使用formatSpec格式化运算符指定指数中的位数?

[英]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. 我正在使用Matlab中的fprintf命令将数据写入输出文本文件。 How to write a number to the output file, for instance, 1.12345678e-001 , with three digits in the exponent ? 如何将数字写入输出文件,例如, 1.12345678e-001指数中有三位数

formatSpec = '%1.8e\n';

gives 1.12345678e-01 , not the desired result! 给出1.12345678e-01 ,不是理想的结果!

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 这里有一个类似的问题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 . 正指数包括加号,与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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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