Logical indexing in cell array

50 vues (au cours des 30 derniers jours)
matuser123
matuser123 le 14 Oct 2016
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'.

Réponse acceptée

Image Analyst
Image Analyst le 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'))

Plus de réponses (3)

Ganesh Hegade
Ganesh Hegade le 14 Oct 2016
Hi, You can use this
strcmp(b, '3');
  1 commentaire
matuser123
matuser123 le 14 Oct 2016
Great! Thanks.
find(strcmp(b,'3')==1)

Connectez-vous pour commenter.


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

Connectez-vous pour commenter.


Sulaymon Eshkabilov
Sulaymon Eshkabilov le 4 Juil 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.

Catégories

En savoir plus sur Matrices and Arrays dans Help Center et File Exchange

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by