使用 ismember 列出所有索引
List all index using ismember
假设我有两个数组:
A:14 63 13
38 44 23
11 12 13
38 44 23
B:38 44 23
我正在尝试使用 ismember
到 return 在 A
中找到 B
的每个位置的索引。我在网上找到的所有示例都只列出匹配项的第一次或最后一次出现,我试图为所有匹配的值(甚至是重复值)创建一个列表索引。谢谢
您可以使用 bsxfun
进行比较:
idx = find( all( bsxfun(@eq, A, B), 2 )); %// only where all line matches
结果
idx =
2
4
将 ismember
与 'rows'
参数一起使用:
ismember(A, B, 'rows')
这会产生一个逻辑数组 [0 1 0 1]
,这通常比索引数组更好,但如果你想要特定的索引,那么只需使用 find
:
find(ismember(A,B,'rows'))
到return[2,4]
请注意,如果 B
有多行,此方法仍然有效,例如B = [38 44 23; 11 12 13]
,会return[0; 1; 1; 1]
这只是 的改进版本,用于处理 B
的多行
idx = find(any(all( bsxfun(@eq, A, permute(B,[3 2 1])), 2 ),3));
样本运行:
A = [14 63 13;
38 44 23;
11 12 13;
38 44 23];
B = [38 44 23;
11 12 13];
idx = find(any(all( bsxfun(@eq, A, permute(B,[3 2 1])), 2 ),3));
>> idx
idx =
2
3
4
如果你有 A 和 B 作为 Nx3
大小的数组,你可以查看 pdist2
-
[indA,indB] = ind2sub([size(A,1) size(B,1)],find(pdist2(A,B)==0));
ind = [indA,indB]
因此,在 ind
中,您将获得匹配的成对索引,第一列代表 A
的索引,第二列代表 B
.
样本运行-
A =
14 63 13
38 44 23
11 12 13
14 63 13
38 44 23
B =
38 44 23
14 63 13
ind =
2 1
5 1
1 2
4 2
假设我有两个数组:
A:14 63 13
38 44 23
11 12 13
38 44 23
B:38 44 23
我正在尝试使用 ismember
到 return 在 A
中找到 B
的每个位置的索引。我在网上找到的所有示例都只列出匹配项的第一次或最后一次出现,我试图为所有匹配的值(甚至是重复值)创建一个列表索引。谢谢
您可以使用 bsxfun
进行比较:
idx = find( all( bsxfun(@eq, A, B), 2 )); %// only where all line matches
结果
idx =
2
4
将 ismember
与 'rows'
参数一起使用:
ismember(A, B, 'rows')
这会产生一个逻辑数组 [0 1 0 1]
,这通常比索引数组更好,但如果你想要特定的索引,那么只需使用 find
:
find(ismember(A,B,'rows'))
到return[2,4]
请注意,如果 B
有多行,此方法仍然有效,例如B = [38 44 23; 11 12 13]
,会return[0; 1; 1; 1]
这只是 B
idx = find(any(all( bsxfun(@eq, A, permute(B,[3 2 1])), 2 ),3));
样本运行:
A = [14 63 13;
38 44 23;
11 12 13;
38 44 23];
B = [38 44 23;
11 12 13];
idx = find(any(all( bsxfun(@eq, A, permute(B,[3 2 1])), 2 ),3));
>> idx
idx =
2
3
4
如果你有 A 和 B 作为 Nx3
大小的数组,你可以查看 pdist2
-
[indA,indB] = ind2sub([size(A,1) size(B,1)],find(pdist2(A,B)==0));
ind = [indA,indB]
因此,在 ind
中,您将获得匹配的成对索引,第一列代表 A
的索引,第二列代表 B
.
样本运行-
A =
14 63 13
38 44 23
11 12 13
14 63 13
38 44 23
B =
38 44 23
14 63 13
ind =
2 1
5 1
1 2
4 2