在MATLAB中指定打印值的最大宽度

问题描述 投票:0回答:1

sprintf和fprintf的字段宽度参数(例如,“ sprintf('%nf',1234)”中的“ n”)指定字段的minimum宽度。这意味着将填充较短的数字,但在保持指定精度时必须允许较长的数字扩展到指定的字段宽度之外。我正在寻找一种指定maximum字段宽度的方法,以使宽度取代精度。

例如,我希望1234.56、1234.56789和1.2345的宽度为8个字符(包括小数),因此分别打印为1234.560、1234.567和1.234500。

这里是一个类似的问题,但是没有特定于MATLAB的解决方案Specifying maximum printf field width for numbers (truncating if necessary)?

我觉得以前必须有人遇到过这个问题,但是我找不到任何相关的东西。如果存在类似问题,请提供链接。谢谢

matlab printf width truncate
1个回答
1
投票

您可以使用ceil(log10())确定您拥有多少个非浮点数字:

X    = [1234.56, 1234.56789, 1.2345]
% We create an array of string containing the format: 
%[ '%.4f\n'
%  '%.4f\n'
%  '%.7f\n' ]
form = strcat('%.',num2str(8-floor(log10(X)).'+1),'f\n')
% We concatenate this array into one single string and we print the result:
fprintf(reshape(form.',1,[]),X) 

或者您可以使用for循环(使用相同的逻辑):

for x = X
    form = strcat('%.',num2str(8-floor(log10(X))+1),'f\n');
    fprintf(form,x)
end

我们获得:

1234.5600
1234.5679
1.2345000
© www.soinside.com 2019 - 2024. All rights reserved.