Matlab sprintf格式 [英] Matlab sprintf formatting

查看:242
本文介绍了Matlab sprintf格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编辑:我将问题改写得更清楚.

EDIT: I've reworded the question to be clearer.

有人知道一种聪明的方法来使sprintf打印%.6f,且末尾的零被消除"吗?这就是我要寻找的:

Does anyone know a clever way to get sprintf to print "%.6f with trailing zeros elminated"? This is what I'm looking for:

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

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

where %somemagic is some magical specifier. None of the formats seem to work.

% 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更改说明符或使用正则表达式删除尾随零以外,我认为没有其他方法可以做到.但是你永远不知道,人群比我聪明.

I don't think there is a way to do it other than looping through each element and changing the specifier based off of mod(x,1)==0 or using regexp to remove trailing zeros. But you never know, the crowd is more clever than I.

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

My actual application is to print out the array elements in an html table. This is my current clunky solution:

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

推荐答案

编辑:已更新为解决已编辑的问题...

Updated to address the edited question...

我认为没有任何方法可以为 SPRINTF ,但是您可以使用功能 NUM2STR REGEXPREP :

I don't think there's any way to do it with a particular format string for SPRINTF, but you could instead try this non-loop approach using the functions NUM2STR and REGEXPREP:

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

这篇关于Matlab sprintf格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆