MATLAB search cell array for a subset of strings

I am trying to find the places where the substring is found in an array of cells in MATLAB. The code below works, but is pretty ugly. It seems to me that there should be a simpler 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.

+5
source share
2 answers

What needs to be done is to encapsulate this idea as a function. Or built-in:

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'
+7
source

, , , - . cellArray, 'words' , :

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

matches = 

    'nicewords'    'morewords'
+4

All Articles