通过ismember查找所有索引 [英] Finding all indices by ismember

查看:62
本文介绍了通过ismember查找所有索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是 ismember 的示例之一中描述的内容:

定义两个具有相同值的向量.

A = [5 3 4 2]; B = [2 4 4 4 6 8];

确定A中的哪些元素也在B中以及它们在B中的对应位置.

[Lia,Locb] = ismember(A,B)

结果是:

Lia =
     0     0     1     1

Locb =    
     0     0     2     1

B中具有与A(3)匹配的最低索引的元素是B(2). A(4)等于B(1).有没有一种方法可以找到 all 匹配A中相同元素的B元素的索引?

解决方案

您可以将输入参数交换为ismember:

[tf, ia] = ismember(B, A)

以您的示例为例,您应该获得:

tf =
     1     1     1     1     0     0

ia = 
     4     3     3     3     0     0

这样,您只需执行以下操作即可查找等于A(3)B所有元素的索引:

find(ia == 3)

这是一般情况下的一个很好的解决方案:

[tf, ia] = ismember(B, A);
idx = 1:numel(B);
ib = accumarray(nonzeros(ia), idx(tf), [], @(x){x});

请注意,输出为单元格数组.对于您的示例,您应该获得:

ib = 
    []
    []
    [2     3     4]
    [      1]

表示B中没有匹配A(1)A(2)的元素,A(3)匹配元素B(2)B(3)B(4)的元素,并且A(4)等于B(1). /p>

This is what is described in one of the examples for ismember:

Define two vectors with values in common.

A = [5 3 4 2]; B = [2 4 4 4 6 8];

Determine which elements of A are also in B as well as their corresponding locations in B.

[Lia,Locb] = ismember(A,B)

The result is:

Lia =
     0     0     1     1

Locb =    
     0     0     2     1

The element in B with the lowest index that matches A(3) is B(2). A(4) equals B(1). Is there a way by which we could find all the indices of the elemets of B matching the same element in A?

解决方案

You can swap the input arguments to ismember:

[tf, ia] = ismember(B, A)

For your example, you should get:

tf =
     1     1     1     1     0     0

ia = 
     4     3     3     3     0     0

This allows you to find, say, the indices of all the elements of B that equal A(3) simply by doing:

find(ia == 3)

Here's a nifty solution for the general case:

[tf, ia] = ismember(B, A);
idx = 1:numel(B);
ib = accumarray(nonzeros(ia), idx(tf), [], @(x){x});

Note that the output is a cell array. For your example, you should get:

ib = 
    []
    []
    [2     3     4]
    [      1]

which means that there are no elements in B matching A(1) and A(2), A(3) matches elements B(2), B(3) and B(4), and A(4) equals B(1).

这篇关于通过ismember查找所有索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆