Tim Taurit
Tim Taurit

Reputation: 9299

Does matrix contain a vector?

I'm looking for a fast / concise way to check whether some matrix contains given vector, e.g.:

 bigMatrix = [1 1 1; 2 2 2; 4 4 4; 5 5 5];

 someFunction(bigMatrix, [1 1 1]) % = true
 someFunction(bigMatrix, [3 3 3]) % = false

Is there such function/operator, or I need a loop?

Upvotes: 2

Views: 251

Answers (1)

Colin T Bowers
Colin T Bowers

Reputation: 18580

I would suggest the following solution:

bigMatrix = [1 1 1; 2 2 2; 4 4 4; 5 5 5];
Vec = [2 2 2];
Index = ismember(bigMatrix, Vec, 'rows');

The result?

Index =

 0
 1
 0
 0

ismember is an incredibly useful function that checks whether the elements of one set are in another set. Here, I exploit the rows option to force the function to compare rows, rather than individual elements.

UPDATE: On the other hand, it is always worth doing a few speed tests! I just compared the ismember approach to the following alternative method:

N = size(bigMatrix, 1);
Index2 = zeros(N, 1);
for n = 1:N
    if all(bigMatrix(n, :) == Vec)
        Index2(n) = 1;
    end
end

My findings? The size of bigMatrix matters! In particular, if bigMatrix is on the small side (somewhat of a misnomer), then the loop is much faster. The first approach is preferable only when bigMatrix becomes big. Further, the results are also dependent on how many columns bigMatrix has, as well as rows! I suggest you test both approaches for your application and then go with whichever is faster. (EDIT: This was on R2011a)

General Note: I am continually surprised by how much faster Matlab's loops have gotten in the last few years. Methinks vectorized code is no longer the holy grail that it once was.

Upvotes: 10

Related Questions