2012-02-24 40 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