5

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.

Community
  • 1
  • 1
dgmp88
  • 537
  • 6
  • 13

2 Answers2

7

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'
Chris Taylor
  • 46,912
  • 15
  • 110
  • 154
  • Cheers! That works, but the thing is I was hoping there'd a be built in function for this, or at least a way to do it in less steps. If someone comes up with something great, if not I'll mark this as a solution in a few hours. – dgmp88 Feb 24 '12 at 12:27
  • As far as I know there's no built-in function. I had the same problem myself a while back, and ended up writing these code snippets because I couldn't find a built-in that did what I wanted. – Chris Taylor Feb 24 '12 at 13:38
4

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'
gnovice
  • 125,304
  • 15
  • 256
  • 359
  • Excellent solution, but I'm terrified of regular expressions. It is less lines of code, but I've marked the above correct as I'd rather avoid regexp. Sorry, that feels a little unfair as this is correct and in a sense simpler. – dgmp88 Feb 24 '12 at 16:01
  • @dgmp88: I understand completely. Regular expressions do take some getting used to, but once you get the hang of them you [feel like a superhero](http://xkcd.com/208/). ;) – gnovice Feb 24 '12 at 16:05