我试图在 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);
这类似于,但不一样this https://stackoverflow.com/questions/9371735/counting-the-occurrences-of-a-string-in-a-cell-array-of-strings-in-matlab and this https://stackoverflow.com/questions/8061344/how-to-search-for-a-string-in-cell-array-in-matlab.
要做的就是将这个想法封装成一个函数。要么内联:
substrmatch = @(x,y) ~cellfun(@isempty,strfind(y,x))
findmatching = @(x,y) y(substrmatch(x,y))
或者包含在两个 m 文件中:
function idx = substrmatch(word,cellarray)
idx = ~cellfun(@isempty,strfind(word,cellarray))
and
function newcell = findmatching(word,oldcell)
newcell = oldcell(substrmatch(word,oldcell))
所以现在你只需输入
>> findmatching('words',cellArray)
ans =
'nicewords' 'morewords'
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)