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
  1 件のコメント
dsmalenb
dsmalenb 2021 年 9 月 12 日
Thank you @Dave B for this answer. I just needed a little nudge in the right direction. :)

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeAxis Labels についてさらに検索

製品


リリース

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by