find a string element in a structure matrix

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

Jan
Jan 2012년 3월 13일
FIND replies a vector of indices. Therefore "find()>0" is not working.

댓글을 달려면 로그인하십시오.

 채택된 답변

Jan
Jan 2012년 3월 13일

1 개 추천

The shown data cannot be a matrix, because a matrix must have a rectangular shape. I assume you mean a cell string:
C = {'abc', 'defg', 'hi'};
Then:
if any(strcmp(C, 'abc'))
disp('abc found');
end

추가 답변 (2개)

sworland
sworland 2015년 12월 3일

36 개 추천

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

vettel liu
vettel liu 2017년 9월 28일
Very helpful! Thank you so much.
Adam Thodey
Adam Thodey 2018년 11월 23일
Fantastic. just what i was looking for!
Alex Lord
Alex Lord 2019년 9월 30일
Fantastic! Was searching for ages
Thanks
gao yang
gao yang 2020년 10월 15일
Merci!!!!
dan
dan 2021년 3월 10일
Perfect! Thanks.

댓글을 달려면 로그인하십시오.

Geoff
Geoff 2012년 3월 13일

1 개 추천

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

Jan
Jan 2012년 3월 13일
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
eliza 2012년 3월 15일
thank you!

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터File Exchange에서 Matrices and Arrays에 대해 자세히 알아보기

질문:

2012년 3월 13일

댓글:

dan
2021년 3월 10일

Community Treasure Hunt

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

Start Hunting!

Translated by