poster
2019-12-10, 20:30
在字符串的单元格数组上使用带有标记的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' 我知道在S中每个单元格字符串只有一个匹配项。如何将该输出转换为矢量化形式的字符串单元格数组?
回答:
这个问题比你想的还要严重。您从REGEXP的 (http://www.mathworks.com/access/helpdesk/help/techdoc/ref/regexpi.html)输出实际上是一个字符串的单元格数组的一个单元格数组的一个单元格数组 !是的,三个级别!以下使用CELLFUN (http://www.mathworks.com/access/helpdesk/help/techdoc/ref/cellfun.html)摆脱了前两个级别,只剩下一个单元格字符串数组:
cellArrayOfStrings = cellfun(@(c) c{1},res); 但是,您也可以将对 (http://www.mathworks.com/access/helpdesk/help/techdoc/ref/vertcat.html) REGEXP (http://www.mathworks.com/access/helpdesk/help/techdoc/ref/regexpi.html)的调用更改为摆脱一个级别,然后使用VERTCAT (http://www.mathworks.com/access/helpdesk/help/techdoc/ref/vertcat.html) :
res = regexp(S,'(\d)','tokens','once'); %# Added the 'once' option cellArrayOfStrings = vertcat(res{:});
更多&回答... (https://stackoverflow.com/questions/2624744)
S = {'string 1';'string 2';'string 3'}; res = regexp(S,'(\d)','tokens') res = {1x1 cell} {1x1 cell} {1x1 cell} res{2}{1} ans = '2' 我知道在S中每个单元格字符串只有一个匹配项。如何将该输出转换为矢量化形式的字符串单元格数组?
回答:
这个问题比你想的还要严重。您从REGEXP的 (http://www.mathworks.com/access/helpdesk/help/techdoc/ref/regexpi.html)输出实际上是一个字符串的单元格数组的一个单元格数组的一个单元格数组 !是的,三个级别!以下使用CELLFUN (http://www.mathworks.com/access/helpdesk/help/techdoc/ref/cellfun.html)摆脱了前两个级别,只剩下一个单元格字符串数组:
cellArrayOfStrings = cellfun(@(c) c{1},res); 但是,您也可以将对 (http://www.mathworks.com/access/helpdesk/help/techdoc/ref/vertcat.html) REGEXP (http://www.mathworks.com/access/helpdesk/help/techdoc/ref/regexpi.html)的调用更改为摆脱一个级别,然后使用VERTCAT (http://www.mathworks.com/access/helpdesk/help/techdoc/ref/vertcat.html) :
res = regexp(S,'(\d)','tokens','once'); %# Added the 'once' option cellArrayOfStrings = vertcat(res{:});
更多&回答... (https://stackoverflow.com/questions/2624744)