MATLAB搜索字符串子集的单元格数组

dgm*_*p88 5 string matlab cell

我试图找到MATLAB中单元格数组中出现子字符串的位置.下面的代码有效,但相当丑陋.在我看来应该有一个更容易的解决方案.

cellArray = [{'these'} 'are' 'some' 'nicewords' 'and' 'some' 'morewords'];
wordPlaces = cellfun(@length,strfind(cellArray,'words'));
wordPlaces = find(wordPlaces); % Word places is the locations.
cellArray(wordPlaces);
Run Code Online (Sandbox Code Playgroud)

这是类似的,但不一样的这个这个.

Chr*_*lor 7

要做的是将这个想法封装为一个功能.内联:

substrmatch = @(x,y) ~cellfun(@isempty,strfind(y,x))

findmatching = @(x,y) y(substrmatch(x,y))
Run Code Online (Sandbox Code Playgroud)

或包含在两个m文件中:

function idx = substrmatch(word,cellarray)
    idx = ~cellfun(@isempty,strfind(word,cellarray))
Run Code Online (Sandbox Code Playgroud)

function newcell = findmatching(word,oldcell)
    newcell = oldcell(substrmatch(word,oldcell))
Run Code Online (Sandbox Code Playgroud)

所以现在你可以输入

>> findmatching('words',cellArray)
ans = 
    'nicewords'    'morewords'
Run Code Online (Sandbox Code Playgroud)