2015-02-05 79 views
0

我試圖找到特定字符串出現在單元格數組中的行索引列表。例如,對於下面的單元陣列:查找特定字符串出現在單元格數組中的行索引

input = {[546] 'Blah blah blah' 
     [783] 'Magic string' 
     [1341] 'Blah, blah, other stuff' 
     [1455] 'Magic string' 
     [1544] 'Another irrelevant string' 
     [1700] 'Yet another pointless string' 
     [1890] 'Magic string'} 

...如果我想查找的字符串'Magic string',返回的這些行的索引,我希望有一個載體來結束:

output = 

     2 4 7 

...因爲'Magic string'存在於input的第2,第4和第7行。

我曾嘗試做如下:

output = strfind({input{:,2}},'Magic string'); 
output = cell2mat(output); 
output = find(output); 

然而,這未能在第二條線,在運行cell2mat()操作時,因爲它消除了所有的空格,而不是返回NaN這些細胞。我不能在單元陣列上運行一個isnan()操作,那麼我該如何實現它呢?

回答

1

對於輸入

input = {[546] 'Blah blah blah' 
     [783] 'Magic string' 
     [1341] 'Blah, blah, other stuff' 
     [1455] 'Magic string' 
     [1544] 'Another irrelevant string' 
     [1700] 'Yet another pointless string' 
     [1890] 'Magic string'} 

只使用

output = find(strcmp(input(:,2), 'Magic string')); 

或者,如果字符串可以在出現任何柱,

output = find(any(strcmp(input, 'Magic string'), 2)); 

的關鍵是,strcmp可以應用到不僅包含字符串單元陣列。對於包含除字符串以外任何內容的單元格,它僅返回0

0

你可以使用正則表達式來解析單元陣列:

clear 
clc 
input = {[546] 'Blah blah blah' 
     [783] 'Magic string' 
     [1341] 'Blah, blah, other stuff' 
     [1455] 'Magic string' 
     [1544] 'Another irrelevant string' 
     [1700] 'Yet another pointless string' 
     [1890] 'Magic string'} 


    CheckString = 'Magic string'; 

    %// Check for the string of interest 
    Indices = regexp(CheckString,input(:,2)) 

指數現在是一個單元陣列。你可以得到行像這樣, 儘管空單元格保留的位置:

Indices = 

    [] 
    [1] 
    [] 
    [1] 
    [] 
    [] 
    [1] 

    Indices = ~cellfun(@isempty,Indices); 

    %// Use find to get the rows: 

    output = find(Indices) 

其中給出:

output = 

    2 
    4 
    7 
相關問題