tags:

views:

81

answers:

1

Hi I am trying to perform a comparison between the rows of two matrices A and B with the same number of columns. In matlab the command "ismember(a, b, 'rows')" returns a vector containing 1 where the rows of A are also rows of B and 0 otherwise, and also returns the highest index in B for each element in A that is a member of B.

[tf, index] = ismember(A, B, 'rows');

is there an equivalent function in python? any ideas how to do it? Thanks

+2  A: 

you can get your vector as

same_rows = [a == b for a,b in zip(A, B)]

Note that this will yield True and False instead of 1 and 0 but bool is subclassed from int and True == 1 and False == 0.

to get the max row where this occurs, you can just use

max_row = next(i for i, row in enumerate(reversed(same_rows)) if row == True)

If you want the number of rows that they have in common, you can just use

same_count == sum(same_rows)

Note that this is all for python and assumes that matrices are lists of lists or tuples or tuples of lists or tuples. HTH.

aaronasterling
or you could just use `map( eq, A, B)` using `eq` from `operator`, also note in Python 3.x that bool is no longer an int but it's own type.
wheaties
@wheaties, good looking out. updated.
aaronasterling
@wheaties: bool is still an int, in Python 3. In fact, `issubclass(bool, int)` returns True. You can have a look at the full discussion: http://stackoverflow.com/questions/2764017/is-false-0-and-true-1-in-python-an-implementation-detail-or-guaranteed-by-t
EOL
@EOL better looking out ;) updated again
aaronasterling
@EOL I stand corrected.
wheaties
Note that same_rows = [a == b for a,b in zip(A, B)], gives me yield only True where the rows are equal only at corresponding rows (e.g a[0,:] = b[0,:]) but i need to find all the positions where a row of a is in b.
Cristina
Kenny, yes I am using Numpy
Cristina