通过sprintf()和fprintf()的Matlab ShortEng数字格式? [英] Matlab ShortEng number format via sprintf() and fprintf()?
问题描述
我喜欢在交互式命令窗口中使用MATLAB的shortEng
表示法:
I like using MATLAB's shortEng
notation in the interactive Command Window:
>> a = 123e-12;
>> disp(a);
1.2300e-10 % Scientific notation. Urgh!
>> format shortEng;
>> disp(a);
123.0000e-012 % Engineering notation! :-D
但是我想使用fprintf:
But I want to use fprintf:
>> format shortEng;
>> fprintf('%0.3e', a);
1.2300e-10 % Scientific. Urgh!
如何使用MATLAB 格式运算符?
How do I print values with fprintf or sprintf with Engineering formatting using the MATLAB Format Operators?
我知道我可以编写自己的函数以将值格式化为字符串,但是我正在寻找已经内置在MATLAB中的东西.
I know I could write my own function to format the values into strings, but I'm looking for something already built into MATLAB.
注意:工程"表示法与科学"表示法的不同之处在于,指数始终是3的倍数.
NOTE: "Engineering" notation differs from "Scientific" in that the exponent is always a multiple of 3.
>> fprintf('%0.3e', a); % This is Scientific notation.
1.230000e-10
推荐答案
无法直接将fprintf
格式说明符用于所需的格式.一种解决方法是将disp
的输出用作要打印的字符串.但是disp
不返回字符串,而是直接写入标准输出.那么,该怎么做呢?
There is no way to use directly fprintf
format specifier for the format you require. A way around is to use the output of disp
as a string to be printed. But disp
doesn't return a string, it writes directly to the standard output. So, how to do this?
在这里evalc
(带有捕获输出的信息)可以进行救援:
Here's where evalc
(eval with capture of output) comes to the rescue:
%// Create helper function
sdisp = @(x) strtrim(evalc(sprintf('disp(%g)', x)));
%// Test helper function
format ShortEng;
a = 123e-12;
fprintf(1, 'Test: %s', sdisp(a));
当然,这是一种解决方法,由于辅助功能的未经测试的输入,它可能会以多种方式适得其反.但这说明了这一点,并且是被指责的eval
函数族实际上不可替代的罕见情况之一.
This is a workaround, of course, and can backfire in multiple ways because of the untested inputs of the helper functions. But it illustrates a point, and is one of the rare occasions where the reviled eval
function family is actually irreplaceable.
这篇关于通过sprintf()和fprintf()的Matlab ShortEng数字格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!