簡體   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