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

11 views (last 30 days)
dsmalenb on 12 Sep 2021
Commented: dsmalenb on 12 Sep 2021
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 on 12 Sep 2021
Edited: Dave B on 12 Sep 2021
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
dsmalenb on 12 Sep 2021
Thank you @Dave B for this answer. I just needed a little nudge in the right direction. :)

Categories

Find more on Matrix Indexing in Help Center and File Exchange

R2020b

Community Treasure Hunt

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

Start Hunting!