简体   繁体   English

将数组合并为一个字符串(matlab)

[英]Combining array into one string (matlab)

I have something like the following: 我有类似以下内容:

A = [1 2 5; 1 5 7];

B = A(1,:);

I output B: 我输出B:

B = A(1,:);

B =

 1     2     5

I am looking to combine what is contained in B into one single string: 我想将B中包含的内容合并为一个字符串:

1/2/5

You can use sprintf : 您可以使用sprintf

sprintf('%d/',B)

This will give you almost what you want, it will have unnecessary / in the end. 这会给你几乎你想要什么,就会产生不必要的/到底。

>> sprintf('%d/',B)

ans =

1/2/5/

If you want to remove it: 如果要删除它:

st = sprintf('%d/',B);
st(end) = [];

As @hmuster points out correctly, it is possible to do it with \\b , the backspace character. 正如@hmuster正确指出的那样,可以使用\\b (退格字符)来实现。

st = [sprintf('%d/',B) sprintf('\b')];

However, as @AndrewJanke points out correctly, it could become a problem if this string is written into a pipe or a file. 但是,正如@AndrewJanke正确指出的那样,如果将此字符串写入管道或文件中,可能会成为问题。 So use it with caution. 因此,请谨慎使用。

If you want it done properly (IE reusable), there are two steps: 如果您希望它正确完成(可重用IE),则有两个步骤:

  1. Convert your numbers to strings (this will allow later crazy values to be converted properly with num2str http://www.mathworks.com/help/matlab/ref/num2str.html 将您的数字转换为字符串(这将允许稍后使用num2str正确转换疯狂的值http://www.mathworks.com/help/matlab/ref/num2str.html

  2. Concatenate your strings horizontally (you can use MATLAB concatenation property A = [BC]), but the functional way is strcat http://www.mathworks.com/help/matlab/ref/strcat.html 水平串联字符串(可以使用MATLAB串联属性A = [BC]),但有效的方法是strcat http://www.mathworks.com/help/matlab/ref/strcat.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM