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?
I would suggest the following solution:
The result?
ismemberis 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
ismemberapproach to the following alternative method:My findings? The size of
bigMatrixmatters! In particular, ifbigMatrixis on the small side (somewhat of a misnomer), then the loop is much faster. The first approach is preferable only whenbigMatrixbecomes big. Further, the results are also dependent on how many columnsbigMatrixhas, 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.