Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MATLAB search cell array for string subset

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.

like image 582
dgmp88 Avatar asked Feb 24 '12 09:02

dgmp88


1 Answers

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'
like image 190
Chris Taylor Avatar answered Oct 05 '22 23:10

Chris Taylor