简体   繁体   English

MATLAB fprintf增加指数位数

[英]MATLAB fprintf Increase Number of Digits of Exponent

If we have A=[100 -0.1 0]; 如果我们有A = [100 -0.1 0]; B=[30 0.2 -2]; B = [30 0.2 -2]; t1='text 1'; t1 ='文字1'; t2=text 2' t2 =文本2'

how to use fprintf so that the output saved in a file will look like that 如何使用fprintf以便保存在文件中的输出看起来像这样

100 -1.000E-0001  0.000E-0000 'text 1' 
30   2.000E-0001 -2.000E-0000 'text 2'

I put together a "one-liner" (spread across several lines for better readability) that takes an array, a single number format, and a delimiter and returns the desired string. 我将一个“单线”(为了更好的可读性而分布在多行上)放在一起,它采用一个数组,一个数字格式和一个定界符并返回所需的字符串。 And while you found the leading blank-space flag, I prefer the + flag, though the function will work with both: 虽然您找到了前导的空格标志,但我更喜欢+标志,尽管该功能可以同时使用以下两种功能:

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]);

Running this yields: 运行此结果:

>> foo
-1.0000E-0001  +0.0000E+0000
+2.0000E-0001  -2.0000E+0000

( foo is just what the script file is called.) foo就是脚本文件的名称。)


Here's a more general approach that searches for the exponential format instead of assuming it: 这是一种搜索指数格式而不是假设它的更通用的方法:

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));

Outputs 输出

>> foo
100  -1.0000E-0001  +0.0000e+0000
 30  +2.0000E-0001  -2.0000e+0000

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

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