如何使用 MATLAB 的 num2str 格式化输出
我正在尝试在 MATLAB 中将数字数组作为字符串输出。我知道使用 num2str
,但我想要逗号后跟空格来分隔数字,而不是制表符。数组元素最多可以精确到十分之几,但其中大多数都是整数。有没有一种方法可以格式化输出,以便省略不必要的尾随零?这是我设法组合在一起的:
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
通过调用来解决这个问题
datastring=strrep(datastring,'.0','')
,但这似乎比我一直在做的更糟糕。
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:
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
datastring=strrep(datastring,'.0','')
but that seems even more kludgey than what I've been doing.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用 MAT2STR 的另一种选择:
使用
2
是精度的位数。Another option using MAT2STR:
with
2
being the number of digits of precision.而不是:
尝试:
输出:
[2,3,5.5,4]
或:
输出:
[2,3,5.5,4]
Instead of:
Try:
Output:
[2, 3, 5.5, 4]
Or:
Output:
[2,3,5.5,4]