2013-12-10 192 views
1

我會使用矩陣B的列,使用第三列過濾矩陣A. 請注意,第三列的值由逗號分隔。Matlab - 如何使用矩陣來過濾另一個矩陣?

示例:P01存在於矩陣A的第3列,則得到值A1。 其他例如:不返回A2因爲P08或P09不B.

A = {'A1' 5 'P01,P02,P03,P04'; 'A2' 7 'P08,P09'; 'A3' 8 'P07'; 'A4' 8 'P10,P11'}; 
B = {'P01'; 'P07'; 'P10'; 'P11'} 

A = 
    'A1' 5 'P01,P02,P03,P04' 
    'A2' 7 'P08,P09' 
    'A3' 8 'P07' 
    'A4' 8 'P10,P11' 

B = 
    'P01' 
    'P07' 
    'P10' 
    'P11' 
    'P12' 
    'P13' 

存在怎樣才能獲得這樣的結果?

C = 
    'A1' 
    'A3' 
    'A4' 

在此先感謝您的幫助。

+0

和你嘗試過什麼? – bla

+0

這與R有什麼關係? – jonsca

回答

2
aux = cellfun(@(c) A(~cellfun('isempty', strfind(A(:,3), c)), 1), B, 'UniformOutput', 0); 
C = unique(vertcat(aux{:})); 
+0

我還需要得到'c'等於'1'的行。我試過這個,但不工作:... cellfun('isempty',strfind(listAllPara(:3),c)|| c =='1')... – TimeIsNear

+0

@TimeIsNear我沒有看到什麼你的意思是「'c'等於'1'」。什麼是'c'? –

2

我認爲這應該沒問題。

A = {'A1', 5 'P01,P02,P03,P04'; 
    'A2' 7, 'P08,P09'; 
    'A3' 8, 'P07'; 
    'A4' 8, 'P10,P11'}; 

B = {'P01'; 'P07'; 'P10'; 'P11'}; 


size(A) 

C = {}; 

% for each row in A 
for ai = 1:size(A, 1) 

    rowA = A(ai, :); 

    firstCol = rowA{1}; 
    thirdCol = rowA{3}; 

    % search if any element of B belongs to string in thirdCol 
    searchResult = cellfun(@(bv) ~isempty(findstr(bv, thirdCol)), B, ... 
             'UniformOutput', false); 

    % change results to matrix 
    searchResult = cell2mat(searchResult)'; 


    % if any element of B in thirdCol then add firstCol to C 
    if any(searchResult) == 1 
     C{end + 1} = firstCol; 
    end 

end 



C 

% gives 
C = 

    'A1' 
    'A3' 
    'A4' 
+0

感謝您的回答,以及非常好的代碼,但是當我搜索「P0」時,我將獲得所有行。雖然結果應該是空的。 – TimeIsNear