登录论坛

查看完整版本 : 如何使用MATLAB的num2str格式化输出


poster
2019-12-10, 20:41
我试图在MATLAB中将数字数组输出为字符串。我知道使用num2str (http://www.mathworks.com/access/helpdesk/help/techdoc/ref/num2str.html)可以很容易地做到这一点,但是我想用逗号后跟一个空格来分隔数字,而不是制表符。数组元素最多具有十分之一的分辨率,但其中大多数将是整数。有没有一种方法可以格式化输出,以便避免不必要的尾随零?这是我设法汇总的内容:

data=[2,3,5.5,4]; datastring=num2str(data,'%.1f, '); datastring=['[',datastring(1:end-1),']'] 它给出了输出:

[2.0, 3.0, 5.5, 4.0] 而不是:

[2, 3, 5.5, 4] 有什么建议么?

编辑:我刚刚意识到我可以使用strrep (http://www.mathworks.com/access/helpdesk/help/techdoc/ref/strrep.html)通过调用来解决此问题

datastring=strrep(datastring,'.0','') 但这似乎比我一直在做的还要笨拙。



回答:

代替:

datastring=num2str(data,'%.1f, '); 尝试:

datastring=num2str(data,'%g, '); 输出: [2, 3, 5.5, 4]

要么:

datastring=sprintf('%g,',data); 输出: [2,3,5.5,4]



更多&回答... (https://stackoverflow.com/questions/3057618)