user2680312
user2680312

Reputation: 53

How to find column in matrix which has contents equal to vector

I have a n x 1 vector V and a n x d matrix M. I know that V is equivalent to one of the columns of M. How can I find the index of M which corresponds to V? I've tried ismember and find but I cannot think of the solution.

Upvotes: 1

Views: 108

Answers (2)

Dan
Dan

Reputation: 45762

An alternative to ismember is using bsxfun:

find(all(bsxfun(@eq, V, M)))

Here bsxfun applies the @eq operation (i.e. ==) to V and every column of M. We then use all to make sure that the entire column matched and finally find to convert from the logical vector to the column index.

Upvotes: 2

Jonas
Jonas

Reputation: 74940

ismember allows looking for 1-by-d vectors in a nxd matrix. All we need to do to make it work for your problem is transposing arrays:

[~, columnIdx] = ismember( nByOneVector.', nByDMatrix.', 'rows');

Upvotes: 3

Related Questions