Index of value when you want to check multiple elements at the same time between 2 cell arrays

조회 수: 6 (최근 30일)
Hello,
I have an M-by-1 cell array, A and a N-by-1 cell array B. I would like to find the indices where each entry of B can be found in A. However, the only way I have gotten my approach to work is looking for a specific entry of B at a time within a loop. I suspect that there is a way to do this without the loop but I am not sure how.
Also, any elements that are in B but are not in A should provide an empty cell. My poor attempt at solving this is below:
A = {'Mary'; 'had'; 'a'; 'little'; 'lamb'};
B = {'Mary'; 'lamb'; 'ary'};
idx = find(ismember(A,B))

채택된 답변

Dave B
Dave B 2021년 9월 12일
편집: Dave B 2021년 9월 12일
If I understand the quesiton, you want to find indices in A where the values in B are found when they are in A.
You can use the second output of ismember for this, it'll return a 0 for items that aren't found:
A = {'Mary'; 'had'; 'a'; 'little'; 'lamb'};
B = {'Mary'; 'lamb'; 'ary'};
[~,idx] = ismember(B,A)
idx = 3×1
1 5 0
Worth pointing out that B might be in A more than once, ismember will return the first place it's found (the documentation says this is 'Generally' true, though I'm not sure I can think of a case where it's not):
A = {'Mary'; 'had'; 'a'; 'little'; 'Mary'};
B = {'Mary';'little';'sheep'};
[~,idx] = ismember(B,A)
idx = 3×1
1 4 0

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Axis Labels에 대해 자세히 알아보기

제품


릴리스

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by