siegel
siegel

Reputation: 829

Find column locations of vector elements inside a matrix

Given a vector such as a = [2 5 9] and a matrix such as

    8  11  5 
b = 2   6  1
    4   9  3

What's the best way to find which column of b contains each element of a? In this example I'd want an output like [1 3 2] because 2 is in the first column, 5 is in the third column, and 9 is in the second column. For my purposes it's safe to assume that a number can only appear in one column.

Upvotes: 2

Views: 75

Answers (3)

Divakar
Divakar

Reputation: 221714

One approach -

[colID,~] = find(squeeze(any(bsxfun(@eq,b,permute(a,[1 3 2])),1)))

Or if you would like to avoid squeeze and any -

[~,colID,~] = ind2sub([size(b) numel(a)],find(bsxfun(@eq,b(:),a)))

Upvotes: 4

rayryeng
rayryeng

Reputation: 104555

Another way would be to use ismember:

A = [2 5 9];
B = [8 11 5; 2 6 1; 4 9 3];
[~, ind] = ismember(A,B);
[~, col] = ind2sub(size(B), ind)

col = 

1   3   2

Upvotes: 3

scmg
scmg

Reputation: 1894

Another approach:

[~, index] = ismember(a, b);
[row, col] = ind2sub(size(b, 1), index);

Upvotes: 2

Related Questions