![](/img/trans.png)
[英]In Matlab, how to specify number of digits in the exponent using formatSpec formatting operator?
[英]MATLAB fprintf Increase Number of Digits of Exponent
如果我们有A = [100 -0.1 0]; B = [30 0.2 -2]; t1 ='文字1'; t2 =文本2'
如何使用fprintf以便保存在文件中的输出看起来像这样
100 -1.000E-0001 0.000E-0000 'text 1'
30 2.000E-0001 -2.000E-0000 'text 2'
我将一个“单线”(为了更好的可读性而分布在多行上)放在一起,它采用一个数组,一个数字格式和一个定界符并返回所需的字符串。 虽然您找到了前导的空格标志,但我更喜欢+
标志,尽管该功能可以同时使用以下两种功能:
A=[-0.1 0];
B=[0.2 -2];
minLenExp = 4;
extsprintf = @(num,fmt,delim) ...
strjoin(cellfun(...
@(toks)[toks{1},repmat('0',1,max([0,minLenExp-length(toks{2})])),toks{2}],...
regexp(sprintf(fmt,num),'([+-\s][\.\d]+[eE][+-])(\d+)','tokens'),...
'UniformOutput',false),delim);
Astr = extsprintf(A,'%+.4E',' ');
Bstr = extsprintf(B,'%+.4E',' ');
disp([Astr;Bstr]);
运行此结果:
>> foo
-1.0000E-0001 +0.0000E+0000
+2.0000E-0001 -2.0000E+0000
( foo
就是脚本文件的名称。)
这是一种搜索指数格式而不是假设它的更通用的方法:
A=[100 -0.1 0].';
B=[30 0.2 -2];
extsprintf = @(fmt,arr) ...
regexprep(...
sprintf(fmt,arr),...
regexprep(regexp(sprintf(fmt,arr),'([+-\s][\.\d]+[eE][+-]\d+)','match'),'([\+\.])','\\$1'),...
cellfun(@(match)...
cellfun(...
@(toks)[toks{1},repmat('0',1,max([0,minLenExp-length(toks{2})])),toks{2}],...
regexp(match,'([+-\s][\.\d]+[eE][+-])(\d+)','tokens'),...
'UniformOutput',false),...
regexp(sprintf(fmt,arr),'([+-\s][\.\d]+[eE][+-]\d+)','match')));
fmt = '%3d %+.4E %+.4e';
disp(extsprintf(fmt,A));
disp(extsprintf(fmt,B));
输出
>> foo
100 -1.0000E-0001 +0.0000e+0000
30 +2.0000E-0001 -2.0000e+0000
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.