2017-07-28 120 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