Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does matrix contain a vector?

Tags:

matlab

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?

like image 839
Paweł Bulwan Avatar asked Feb 19 '26 03:02

Paweł Bulwan


1 Answers

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.

like image 168
Colin T Bowers Avatar answered Feb 22 '26 03:02

Colin T Bowers



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!