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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 00:46:33  来源:igfitidea点击:

How to format output using MATLAB's num2str

stringmatlabstring-formatting

提问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 strrepto 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);

Output:[2,3,5.5,4]

输出:[2,3,5.5,4]

回答by Amro

Another option using MAT2STR:

使用MAT2STR 的另一种选择:

? datastring = strrep(mat2str(data,2),' ',',')
datastring =
[2,3,5.5,4]

with 2being the number of digits of precision.

2被的精度位数。