find a string element in a structure matrix
Afficher commentaires plus anciens
assume i have a matrix t =
'abc'
'defg'
'hi'
i want to check if 'abc' is in the matrix t
however this code doesnt seem to work
if (find(t == 'abc') >0)
i get the following error message Undefined function or method 'eq' for input arguments of type 'cell'.
1 commentaire
Jan
le 13 Mar 2012
FIND replies a vector of indices. Therefore "find()>0" is not working.
Réponse acceptée
Plus de réponses (2)
sworland
le 3 Déc 2015
I realize that the answer for this was accepted, but the question did say in a "structure matrix", which I interpreted to mean a structure array. For that the following will find the index of the first occurrence,
index = find(strcmp({structname.field}, 'string')==1)
6 commentaires
vettel liu
le 28 Sep 2017
Very helpful! Thank you so much.
Adam Thodey
le 23 Nov 2018
Fantastic. just what i was looking for!
Alex Lord
le 30 Sep 2019
Fantastic! Was searching for ages
Shaul Shvimmer
le 9 Juin 2020
Thanks
gao yang
le 15 Oct 2020
Merci!!!!
dan
le 10 Mar 2021
Perfect! Thanks.
Geoff
le 13 Mar 2012
Direct comparison operators (==, etc) don't work with strings.
You need to use strcmp or strcmpi (which ignores case).
Because that function doesn't work on an array, you need to map it:
isabc = cellfun( @(x) strcmp(x,'abc'), t );
This will give you an array of booleans. If you don't care what index the 'abc' occurred at, but just that it exists, you then do this:
if any(isabc)
% etc
end
To obtain the index of the first occurrence, use this:
firstabc = find( isabc, 1 );
-g-
2 commentaires
Jan
le 13 Mar 2012
The == operator does work with strings, try:
a = 'abc', b = '12c', a==b, a=='b';
The only limitation is that both arguments must have the same size or one must be a scalar.
STRCMPI does accept cell strings as inputs such that the CELLFUN approach is not needed.
eliza
le 15 Mar 2012
Catégories
En savoir plus sur Matrices and Arrays dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!