Find where two cell arrays of different sizes are equal

조회 수: 12 (최근 30일)
Camille Woicekowski
Camille Woicekowski 2020년 9월 22일
댓글: Camille Woicekowski 2020년 9월 22일
I have two cell arrays of different sizes filled with chars. I want to loop through and find the indices of one cell where the char values are equal to each other.
for example,
cell1={'cat','dog','pig','cow','goat'}
cell2={'meow','cat','bark','goat'}
should return 1 and 5 if I loop through cell one.
If these were doubles, I would use
for i=1:size(cell1,2)
ind=find(cell2==cell1(1,i))
end
but with these variable types I'm having some trouble.
cell2{1,2}==cell1{1,1}
return the logcial True but
find(cell2==cell1{1,1})
returns the error message "Operator == is not supported for opperands type cell". I also tried using cellfun(@isequal, cell1, cell2) but I get an error message because the size and shape of my cells are not equal.
How can I get the desired result using these variable types?
  댓글 수: 2
Stephen23
Stephen23 2020년 9월 22일
편집: Stephen23 2020년 9월 22일
"If these were doubles, I would use"
for i=1:size(cell1,2)
ind=find(cell2==cell1(1,i))
end
The MATLAB approach would be to use ismember, e.g.:
>> A = [99,100,112,111,103];
>> B = [109,99,98,103];
>> find(ismember(A,B))
ans =
1 5
Which also works for cell arrays of character vectors:
>> A = {'cat','dog','pig','cow','goat'};
>> B = {'meow','cat','bark','goat'};
>> find(ismember(A,B))
ans =
1 5
Camille Woicekowski
Camille Woicekowski 2020년 9월 22일
Wow, can you tell I learned Python first? Matlab has been all self-taught for me. This is really helpful, thank you!

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

채택된 답변

Ameer Hamza
Ameer Hamza 2020년 9월 22일
편집: Ameer Hamza 2020년 9월 22일
To compare char arrays, strcmp() should be used. However, since you are using the lastest version of MATLAB, so there are easier ways
cell1={'cat','dog','pig','cow','goat'};
cell2={'meow','cat','bark','goat'};
idx = find(any(string(cell1) == string(cell2).'));
Result
>> idx
idx =
1 5
  댓글 수: 3
Ameer Hamza
Ameer Hamza 2020년 9월 22일
Yes, that is the power of MATLAB vectorization. Most of the things can be done without loops.
I am glad to be of help!
per isakson
per isakson 2020년 9월 22일
... or
find( ismember( cell1, cell2 ) )

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

제품


릴리스

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by