在MATLAB中将单元格的单元格数组转换为字符串的单元格数组

yuk*_*yuk 6 regex string matlab cell

在字符串的单元格数组上使用带有标记的regexp,我得到了单元格的单元格数组.这是一个简化的例子:

S = {'string 1';'string 2';'string 3'};
res = regexp(S,'(\d)','tokens')
res = 

    {1x1 cell}
    {1x1 cell}
    {1x1 cell}
res{2}{1}
ans = 
    '2'
Run Code Online (Sandbox Code Playgroud)

我知道在S中每个单元字符串只有一个匹配项.我如何将这个输出转换为矢量化形式的字符串单元格数组?

gno*_*ice 12

问题比你想象的还要糟糕.REGEXP的输出实际上是字符串单元格数组的单元格数组!是的,三个级别!以下使用CELLFUN来摆脱前两个级别,只留下一个字符串的单元格数组:

cellArrayOfStrings = cellfun(@(c) c{1},res);
Run Code Online (Sandbox Code Playgroud)

但是,您也可以将对REGEXP的调用更改为删除一个级别,然后使用VERTCAT:

res = regexp(S,'(\d)','tokens','once');  %# Added the 'once' option
cellArrayOfStrings = vertcat(res{:});
Run Code Online (Sandbox Code Playgroud)