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

9 次查看(过去 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 中查找有关 Matrix Indexing 的更多信息

产品


版本

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by