问题描述
我正在尝试在MATLAB中将数字数组作为字符串输出.我知道使用 num2str
即可轻松完成此操作,但我要在逗号后面加一个空格以分隔数字,而不是制表符.数组元素最多将具有十分之一的分辨率,但其中大多数将是整数.有没有一种格式化输出的方法,可以避免不必要的尾随零?这是我设法整理的:
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),']']
给出输出:
[2.0, 3.0, 5.5, 4.0]
而不是:
[2, 3, 5.5, 4]
有什么建议吗?
编辑:我刚刚意识到可以使用 strrep
通过调用
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.
推荐答案
代替:
datastring=num2str(data,'%.1f, ');
尝试:
datastring=num2str(data,'%g, ');
输出:[2, 3, 5.5, 4]
或:
Output:[2, 3, 5.5, 4]
Or:
datastring=sprintf('%g,',data);
这篇关于如何使用MATLAB的num2str格式化输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!