Matlab sprintf格式化

时间:2011-04-09 20:14:34

标签: matlab printf

编辑:我已将问题改写为更清晰。

有没有人知道一种聪明的方法让sprintf打印“%。6f并删除尾随零”?这就是我要找的东西:

sprintf('%somemagic ', [12345678 123.45])
ans = 1234578 123.45 

其中%somemagic是一些神奇的说明符。这些格式似乎都不起作用。

% no trailing zeros, but scientific for big nums
sprintf('%g ', [12345678 123.45])
ans = 1.23457e+007 123.45 

% not approp for floats
sprintf('%d ', [12345678 123.45])
ans = 12345678 1.234500e+002 

% trailing zeros
sprintf('%f ', [12345678 123.45])
ans = 12345678.000000 123.450000

% cannot specify sig figs after decimal (combo of gnovice's approaches)
mat = [12345678 123.45 123.456789012345];
for j = 1:length(mat)
    fprintf('%s ', strrep(num2str(mat(j),20), ' ', ''));
end

除了循环遍历每个元素并根据mod(x,1)== 0更改说明符或使用regexp删除尾随零之外,我认为没有办法做到这一点。但你永远不知道,人群比我聪明。

我的实际应用是在html表中打印出数组元素。这是我目前笨重的解决方案:

for j = 1:length(mat)
    if mod(mat(j),1) == 0
        fprintf('<td>%d</td>', mat(j));
    else
        fprintf('<td>%g</td>', mat(j));
    end
end

2 个答案:

答案 0 :(得分:4)

编辑:已更新,以解决已修改的问题......

我认为没有任何方法可以使用SPRINTF的特定格式字符串,但您可以使用函数NUM2STRREGEXPREP来尝试这种非循环方法:

>> mat = [12345678 123.45 123.456789012345];       %# Sample data
>> str = num2str(mat,'<td>%.6f</td>');             %# Create the string
>> str = regexprep(str,{'\.?0+<','\s'},{'<',''});  %# Remove trailing zeroes
                                                   %#   and whitespace
>> fprintf(str);                                   %# Output the string

<td>12345678</td><td>123.45</td><td>123.456789</td>  %# Output

答案 1 :(得分:0)

问题在于你将int与数组中的float混合。 Matlab不喜欢这样,所以 将你的int转换为float,以便数组中的所有元素都是相同的类型。看看doc sprintf:你现在被迫在浮动上使用%f,%e或%g

虽然我承认我喜欢上面(或下面)的STRREP方法