swi*_*_on 6 matlab number-formatting
我喜欢shortEng在交互式命令窗口中使用MATLAB的表示法:
>> a = 123e-12;
>> disp(a);
1.2300e-10 % Scientific notation. Urgh!
>> format shortEng;
>> disp(a);
123.0000e-012 % Engineering notation! :-D
Run Code Online (Sandbox Code Playgroud)
但我想使用fprintf:
>> format shortEng;
>> fprintf('%0.3e', a);
1.2300e-10 % Scientific. Urgh!
Run Code Online (Sandbox Code Playgroud)
如何使用MATLAB 格式运算符使用fprintf或sprintf使用工程格式打印值?
我知道我可以编写自己的函数来将值格式化为字符串,但我正在寻找已经内置到MATLAB中的东西.
注意:"工程"符号与"科学"的不同之处在于指数始终是3的倍数.
>> fprintf('%0.3e', a); % This is Scientific notation.
1.230000e-10
Run Code Online (Sandbox Code Playgroud)
小智 5
无法直接fprintf为您需要的格式使用格式说明符。一种解决方法是将 的输出disp用作要打印的字符串。但disp不返回字符串,它直接写入标准输出。那么,如何做到这一点?
这就是evalc(eval with capture of output)可以解决问题的地方:
%// 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));
Run Code Online (Sandbox Code Playgroud)
当然,这是一种解决方法,并且由于辅助函数的输入未经测试,可能会以多种方式适得其反。但它说明了一点,并且是被辱骂的eval函数族实际上不可替代的少数情况之一。
| 归档时间: |
|
| 查看次数: |
2037 次 |
| 最近记录: |