find a string element in a structure matrix
161 次查看(过去 30 天)
显示 更早的评论
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
2012-3-13
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
2015-12-3
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)
Geoff
2012-3-13
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
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.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Cell Arrays 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!