user1926550
user1926550

Reputation: 695

Octave - compare matrix's columns with vector

I have a matrix and a vector and I want to compare each column of the matrix with vector - what i want to get is the number of the column that is equal to vector. Example:

matrix M=1 1 0 1
         1 0 0 0
         0 1 1 0

vector v= 1 0 1

the result should be 2 (since second column of M is equal to vector v)

How do I do that?

Upvotes: 0

Views: 1325

Answers (2)

carandraug
carandraug

Reputation: 13091

use broadcasting (bsxfun), to compare the vector to each of the rows in the matrix. Then find which row is all true

find (all (bsxfun (@eq, m, v')))

Upvotes: 1

Fred Foo
Fred Foo

Reputation: 363627

octave> M = [1 1 0 1; 1 0 0 0; 0 1 1 0];
octave> v = [1 0 1];
octave> sum(M == repmat(v', 1, 4))
ans =

   1   3   2   2

octave> sum(M == repmat(v', 1, 4)) == size(M, 1)
ans =

   0   1   0   0

octave> find(sum(M == repmat(v', 1, 4)) == size(M, 1))
ans =  2

Upvotes: 1

Related Questions