string 在 MATLAB 中将元胞数组转换为字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20463896/
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
Converting an cell array into string in MATLAB
提问by MSD
I was doing some operations in Strings.I have a string 'AGCT' in X.I saved it in a cell using the following command
我在字符串中做一些操作。我在 XI 中有一个字符串 'AGCT' 使用以下命令将它保存在一个单元格中
y(1,1)={x};
Now it is stored in a single cell.Now i want to take each letter from the string separately.I want to take A first the G and so on. Cell array conversion is necessary in this case.So how to convert the cell content back to string again??
现在它存储在一个单元格中。现在我想分别从字符串中取出每个字母。我想先取 A 取 G 等等。在这种情况下需要转换单元格数组。那么如何将单元格内容再次转换回字符串??
回答by chappjc
You can get the string out of a cell with the curly braces ({}
):
您可以使用花括号 ( {}
)从单元格中取出字符串:
x='AGCT';
y(1) = {x};
y{1}
ans =
AGCT
And you can string together indexing operators to get individual characters directly from the cell array. For example:
并且您可以将索引运算符串在一起以直接从元胞数组中获取单个字符。例如:
y{1}(2)
ans =
G
Also keep in mind that the char
function can convert a cell array of strings into a 2D character array by vertically concatenating the strings while padding with white space as necessary:
还要记住,该char
函数可以通过垂直连接字符串同时根据需要填充空白来将字符串元胞数组转换为二维字符数组:
S = char(C)
, whenC
is a cell array of strings, places each element ofC
into the rows of the character arrayS
. UseCELLSTR
to convert back.
S = char(C)
, whenC
是字符串元胞数组,将 的每个元素C
放入字符数组的行中S
。使用CELLSTR
转换回来。
This way you could convert your entire cell array into a 2D character array with just char(y)
, but I think you are looking for a way to do the indexing of individual characters directly from the cell array as above.
通过这种方式,您可以将整个元胞数组转换为 2D 字符数组char(y)
,但我认为您正在寻找一种方法来直接从元胞数组中对单个字符进行索引,如上所述。
And speaking of cell array conversion, have a look at cellfun
, which can be used to perform the same operation on each cell. For example, if you had a cell such as y = {'AGCT','CTGA'};
and you wanted the second character of each cell (a character array containing GT
), you might be tempted to do y{:}(2)
, but this does not work (the first index must be a scalar). A solution is:
说到元胞数组转换,请看cellfun
,它可用于对每个元胞执行相同的操作。例如,如果您有一个像这样的单元格y = {'AGCT','CTGA'};
并且您想要每个单元格的第二个字符(一个包含 的字符数组GT
),您可能很想这样做y{:}(2)
,但这不起作用(第一个索引必须是标量)。一个解决办法是:
>> iBase = 2;
>> basei = cellfun(@(c)c(iBase),y)
basei =
GT