如果我有一个单元格数组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' 在第三栏?
indexresult = [1,4,6]
答案 0 :(得分: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 :(得分:-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))