string 如何使用 MATLAB 的 num2str 格式化输出
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3057618/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to format output using MATLAB's num2str
提问by Doresoom
I'm trying to ouput an array of numbers as a string in MATLAB. I know this is easily done using num2str
, but I wanted commas followed by a space to separate the numbers, not tabs. The array elements will at most have resolution to the tenths place, but most of them will be integers. Is there a way to format output so that unnecessary trailing zeros are left off? Here's what I've managed to put together:
我试图在 MATLAB 中将数字数组作为字符串输出。我知道使用 很容易做到这一点num2str
,但我想要逗号后跟一个空格来分隔数字,而不是制表符。数组元素的分辨率最多为十分之一,但大多数都是整数。有没有办法格式化输出,以便去掉不必要的尾随零?这是我设法整理的内容:
data=[2,3,5.5,4];
datastring=num2str(data,'%.1f, ');
datastring=['[',datastring(1:end-1),']']
which gives the output:
这给出了输出:
[2.0, 3.0, 5.5, 4.0]
rather than:
而不是:
[2, 3, 5.5, 4]
Any suggestions?
有什么建议?
EDIT:I just realized that I can use strrep
to fix this by calling
编辑:我刚刚意识到我可以strrep
通过调用来解决这个问题
datastring=strrep(datastring,'.0','')
but that seems even more kludgey than what I've been doing.
但这似乎比我一直在做的更笨拙。
回答by Jacob
Instead of:
代替:
datastring=num2str(data,'%.1f, ');
Try:
尝试:
datastring=num2str(data,'%g, ');
Output:[2, 3, 5.5, 4]
输出:[2, 3, 5.5, 4]
Or:
或者:
datastring=sprintf('%g,',data);