Logical indexing in cell array

151 views (last 30 days)
Is there a way to search strings in a cell array similar to numeric arrays?
a = [1 2 3 4 5 6];
>> idx = find(a==3)
idx = 3
>> b = {'1' '2' '3' '4' '5' '6'};
>> idx = find(b=='3')
Undefined function 'eq' for input arguments of type 'cell'.

Accepted Answer

Image Analyst
Image Analyst on 14 Oct 2016
Use ismember to search cell arrays:
b = {'1' '2' '3' '4' '5' '6'};
logicalIndex = ismember(b, '3') % Or...
actualIndex = find(ismember(b, '3'))

More Answers (3)

Ganesh Hegade
Ganesh Hegade on 14 Oct 2016
Hi, You can use this
strcmp(b, '3');

michio
michio on 14 Oct 2016
Using cellfun is one way.
b = {'1' '2' '3' '4' '5' '6'};
cellfun(@(x) strcmp(x,'3'), b)
  1 Comment
michio
michio on 14 Oct 2016
Aha, strcmp does accept cell array. Thank Ganesh.

Sign in to comment.


Sulaymon Eshkabilov
Sulaymon Eshkabilov on 4 Jul 2021
Now, what michio suggested works perfectly ok:
b = {'1' '2' '3' '4' '5' '6'};
b(cellfun(@(x) strcmp(x,'3'), b))={'Found 3'}
So this is another good solution for this exercise.

Categories

Find more on Matrices and Arrays in Help Center and File Exchange

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!