2012-02-24 60 views
5

我试图找到一个子字符串在MATLAB单元格数组中出现的位置。下面的代码工作,但相当丑陋。在我看来,应该有一个更简单的解决方案。MATLAB搜索单元格数组的字符串子集

cellArray = [{'these'} 'are' 'some' 'nicewords' 'and' 'some' 'morewords']; 
wordPlaces = cellfun(@length,strfind(cellArray,'words')); 
wordPlaces = find(wordPlaces); % Word places is the locations. 
cellArray(wordPlaces); 

这是类似的,但作为thisthis不一样的。

回答

7

要做的事情就是将这个想法封装为一个函数。内联:

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

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

或包含在两个m文件:

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

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

所以现在你可以只输入

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

干杯!这是有效的,但事情是我希望能够为此创建功能,或者至少有一种方法可以用更少的步骤来完成。如果有人想出了一些好东西,如果没有,我会在几个小时内将其标记为解决方案。 – dgmp88 2012-02-24 12:27:53

+0

据我所知,没有内置功能。我一会儿又遇到了同样的问题,最后写了这些代码片段,因为我找不到我想要的内置内容。 – 2012-02-24 13:38:07

+0

够公平的。我会和这一起去 - 欢呼! – dgmp88 2012-02-24 15:54:30

4

我不知道你是否会认为它是一个比您的解决方案更简单,但regular expressions是我经常用于搜索字符串的非常好的通用实用程序。从cellArray提取细胞的一种方式,它包含与'words'话在他们如下:

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

matches = 

    'nicewords' 'morewords' 
+0

优秀的解决方案,但我很害怕正则表达式。这是更少的代码行,但我已经标记了上面的正确,因为我宁愿避免使用正则表达式。对不起,这感觉有点不公平,因为这是正确的,从某种意义上说更简单。 – dgmp88 2012-02-24 16:01:15

+0

@ dgmp88:我完全理解。正则表达式确实需要一些习惯,但是一旦你掌握了它们,你就会感觉像是一个超级英雄(http://xkcd.com/208/)。 ;) – gnovice 2012-02-24 16:05:47