MATLAB search cell array for string subset

試著忘記壹切 提交于 2019-12-10 14:24:52

问题


I'm trying to find the locations where a substring occurs in a cell array in MATLAB. The code below works, but is rather ugly. It seems to me there should be an easier solution.

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 is similar to, but not the same as this and this.


回答1:


The thing to do is to encapsulate this idea as a function. Either inline:

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

findmatching = @(x,y) y(substrmatch(x,y))

Or contained in two m-files:

function idx = substrmatch(word,cellarray)
    idx = ~cellfun(@isempty,strfind(word,cellarray))

and

function newcell = findmatching(word,oldcell)
    newcell = oldcell(substrmatch(word,oldcell))

So now you can just type

>> findmatching('words',cellArray)
ans = 
    'nicewords'    'morewords'



回答2:


I don't know if you would consider it a simpler solution than yours, but regular expressions are a very good general-purpose utility I often use for searching strings. One way to extract the cells from cellArray that contains words with 'words' in them is as follows:

>> matches = regexp(cellArray,'^.*words.*$','match');  %# Extract the matches
>> matches = [matches{:}]                              %# Remove empty cells

matches = 

    'nicewords'    'morewords'


来源:https://stackoverflow.com/questions/9428746/matlab-search-cell-array-for-string-subset

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!