0

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] 
0

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

-1

YOu can use strfind to get the indices which has string name and then use logical indices to get 23 out of the obtained indices.

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))

1 Comment

Be aware that strfind will also match any strings which contain 'name', such as 'name1234'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.