2017-07-28 121 views
0

如果我有一個單元陣列C查找行索引(Matlab的)

C = {'name' 'hh' '23' []  [] 
    'last' 'bb' '12' '8' 'hello' 
    'In' 'kk' '12' '2131' [] 
    'name' 'kk' '23' []  [] 
    'name' 'cv' '22' []  [] 
    'name' 'ph' '23' []  [] } ; 

我怎樣才能在第一有「名稱」的所有行的行索引列和'23'在第三列?

indexresult = [1,4,6] 

回答

4

做到這一點(所有版本兼容)最簡單的方法是隻用strcmp,它可以接受電池陣列,並做了「字符串比較」。

一個襯墊

indexresult = find(strcmp(C(:,1), 'name') & strcmp(C(:,3), '23')); 
% indexresult = [1; 4; 6]; 

說明

% Get logical array of rows where first column is 'name' 
logicalname = strcmp(C(:,1), 'name'); 
% Get logical array of rows where third column is '23' 
logical23 = strcmp(C(:,3), '23'); 
% Get logical array where both of the above are true, using and (&) 
logicalname23 = strcmp(C(:,1), 'name') & strcmp(C(:,3), '23'); 
% Get indices from logical array using find 
indexresult = find(strcmp(C(:,1), 'name') & strcmp(C(:,3), '23')); 
% If you wanted a row vector instead of column vector, just transpose too 
indexresult = find(strcmp(C(:,1), 'name') & strcmp(C(:,3), '23')).'; 

如果你想不區分大小寫(匹配'name', 'NAME', 'Name', ...),然後使用strcmpi代替strcmp

-1

可以使用strfind獲得具有字符串名稱索引,然後使用邏輯索引得到23把獲得的指標。

C = {'name' 'hh' '23' []  [] 
    'last' 'bb' '12' '8' 'hello' 
    'In' 'kk' '12' '2131' [] 
    'name' 'kk' '23' []  [] 
    'name' 'cv' '22' []  [] 
    'name' 'ph' '23' []  [] } ; 

% find indices of name 
idx = strfind(C(:,1), 'name'); 
idx = find(not(cellfun('isempty', idx))); 
% pick 23 from 3rc column 

iwant =idx((str2double(C(idx,3))==23)) 
+2

請注意,'strfind'也會匹配任何包含*''name''的字符串,例如''name1234'' – Wolfie