繁体   English   中英

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

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

我正在使用Matlab中的fprintf命令将数据写入输出文本文件。 如何将数字写入输出文件,例如, 1.12345678e-001指数中有三位数

formatSpec = '%1.8e\n';

给出1.12345678e-01 ,不是理想的结果!

这里有一个类似的问题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

但按照给出的说明没有解决问题!

您可以使用此非正则表达式方法:

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

ans =
1.12345678e-001

对于多个输入,使用此:

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

不知道这是否属于溶液变通的类别下,但这里有云:

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

它使用正则表达式来标识指数子字符串,并将其替换为零填充到三位数的指数。 正指数包括加号,与fprintf

这不是最干净的答案,但你可以做这样的事情。 基本步骤按原样写入,使用正则表达式获取指数,重写该部分,然后替换。

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)

这输出:

fixedStr =    
1.12345678e-001

暂无
暂无

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

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