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.

2 Answers 2

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'
Sign up to request clarification or add additional context in comments.

2 Comments

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.
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.
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'

2 Comments

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: I understand completely. Regular expressions do take some getting used to, but once you get the hang of them you feel like a superhero. ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.