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))
0 个评论
采纳的回答
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)
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)
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!