non-looping way to compare cellstr arrays of different sizes

Suppose A = {'aa', 'kk', 'ccc'}, B = {'aa', 'bb', 'cc', 'dd', 'ee'}.
Is there a not-explicitly-looping way to return a logical array the same size as A that is 1 where an element of A is in B, 0 where it is not, e.g.,
"whereMember"(A,B) => [1 0 0]?
Thanks!

 채택된 답변

Oleg Komarov
Oleg Komarov 2011년 8월 24일
A = {'aa', 'kk', 'ccc'};
B = {'aa', 'bb', 'cc', 'dd', 'ee'};
ismember(A,B)

댓글 수: 4

DOH! (I've gotten so used to using ismember when the first argument is a scalar I forgot that it could be an array!) :-(
Thanks!
Oh, but wait a sec, I forgot: I'd also like it to be case insensitive, i.e., A = {'Aa', 'kk', 'cc'} would also return [1 0 0]. Sorry!
DG
ismember(lower(A),B)
DOH! again. (But shouldn't that be ismember(lower(A),lower(B)) - I want it to be "commutatively" case insensitive.) :-)
Thanks one more time!
Yes, then lower() both.

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

추가 답변 (1개)

David Goldsmith
David Goldsmith 2011년 8월 24일
Here's a little function that does if the answer to the revised question is "no":
function la = cellstrIsMember(A, B, i)
% la = 1 where the elements of cellstr array A are in cellstr array B, 0 where they are not
% i is an optional parameter: if case matters, i=1 (the default),
% 0 for case-insensitive matching (which is slower)
%
% Author: David Goldsmith, Wash. State Dept. of Ecology, dgol461@ecy.wa.gov
% Release date: 2011-08-24
if nargin < 3
i = 1;
end
if i || isempty(A) || isempty(B)
la = ismember(A, B);
else
la = zeros(size(A));
for i=1:length(A)
if any(strcmpi(A{i}, B))
la(i) = 1;
end
end
end
end

댓글 수: 7

Small suggestions: Using "numel(A)" instead of "length(A)" considers cell arrays of any dimensions.
"la=false(size(A))" replies a logical array as ISMEMBER. Then the loop can be:
for i=1:numel(A), la(i)= any(strcmpi(A{i}, B)); end
BTW.: Your loop is faster than ISMEMBER.
What is the meaning of your otehr thread: http://www.mathworks.com/matlabcentral/answers/13906-indexing-way-to-look-for-specifc-cell-arrays-in-a-cell-array-of-cell-arrays ???
Just elaborated.
Oh, and thanks for the refactoring--very interesting that it's faster; I guess ismember must come w/ a lot more overhead?
Unfortunately yes.
Jan: may I credit you in my by-line comment? If yes, what is your affiliation, if any?
@David: I've tried to let leo.org tell me, what affiliation is. Leo meant, that either somebody adopts me, or that it concerns my fatherhood. :-) If this means my company: I'm a freelancer. Perhaps my FEX author ID 15233 is helpful?

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

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by