If I have a cell array C
:
C = {'name' 'hh' '23' [] []
'last' 'bb' '12' '8' 'hello'
'In' 'kk' '12' '2131' []
'name' 'kk' '23' [] []
'name' 'cv' '22' [] []
'name' 'ph' '23' [] [] } ;
How can I get the row index of all the rows that have 'name' in the first column and '23' in the third column?
indexresult = [1,4,6]
The simplest way to do this (all-versions compatible) would be to just use strcmp
, which can accept cell arrays and does a "string compare".
One liner
indexresult = find(strcmp(C(:,1), 'name') & strcmp(C(:,3), '23'));
% indexresult = [1; 4; 6];
Explanation
% 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')).';
If you want to be case insensitive (matching 'name', 'NAME', 'Name', ...
) then use strcmpi
instead of strcmp
.