Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding all indices by ismember

Tags:

matlab

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?

like image 208
user3077261 Avatar asked Dec 08 '13 11:12

user3077261


People also ask

How to use ismember function Matlab?

Lia = ismember( A , B ) returns an array containing logical 1 ( true ) where the data in A is found in B . Elsewhere, the array contains logical 0 ( false ). If A and B are tables or timetables, then ismember returns a logical value for each row.

How do you find the index of an element in an array in Matlab?

Description. k = find( X ) returns a vector containing the linear indices of each nonzero element in array X . If X is a vector, then find returns a vector with the same orientation as X . If X is a multidimensional array, then find returns a column vector of the linear indices of the result.


1 Answers

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).

like image 147
Eitan T Avatar answered Oct 11 '22 12:10

Eitan T