在元胞数组中查找字符串的行索引(Matlab)

Find row Index of strings in cell Array (Matlab)

如果我有一个元胞数组C:

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

如何获取第一列中具有 'name''23'[=19= 的所有行的行索引]在第三栏?

indexresult = [1,4,6] 

您可以使用 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))

执行此操作的最简单方法(所有版本兼容)就是使用 strcmp,它可以接受元胞数组并执行 "string compare".

一个衬里

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