Function for 'does matrix contain value X?'

106,974

Solution 1

you can do:

A = randi(10, [3 4]);      %# a random matrix
any( A(:)==5 )             %# does A contain 5?

To do the above in a vectorized way, use:

any( bsxfun(@eq, A(:), [5 7 11] )

or as @woodchips suggests:

ismember([5 7 11], A)

Solution 2

If you need to check whether the elements of one vector are in another, the best solution is ismember as mentioned in the other answers.

ismember([15 17],primes(20))

However when you are dealing with floating point numbers, or just want to have close matches (+- 1000 is also possible), the best solution I found is the fairly efficient File Exchange Submission: ismemberf

It gives a very practical example:

[tf, loc]=ismember(0.3, 0:0.1:1) % returns false 
[tf, loc]=ismemberf(0.3, 0:0.1:1) % returns true

Though the default tolerance should normally be sufficient, it gives you more flexibility

ismemberf(9.99, 0:10:100) % returns false
ismemberf(9.99, 0:10:100,'tol',0.05) % returns true

Solution 3

For floating point data, you can use the new ismembertol function, which computes set membership with a specified tolerance. This is similar to the ismemberf function found in the File Exchange except that it is now built-in to MATLAB. Example:

>> pi_estimate = 3.14159;
>> abs(pi_estimate - pi)
ans =
   5.3590e-08
>> tol = 1e-7;
>> ismembertol(pi,pi_estimate,tol)
ans =
     1
Share:
106,974
zenna
Author by

zenna

Electronic Engineer, Biomedical Engineer, C++/CUDA

Updated on July 05, 2022

Comments

  • zenna
    zenna almost 2 years

    Is there a built in MATLAB function to find out if a matrix contains a certain value? (ala PHP's in_array())

  • Jordan
    Jordan almost 10 years
    why are u using [5 7 11] as an argument in ismember
  • Amro
    Amro almost 10 years
    @Jordan: the answer returned is a logical array (true/false) of the same size as the argument, indicating whether the matrix A contains each of those values (e.g [true, true, false] meaning A contains the values 5 and 7 but not 11).
  • Amro
    Amro about 9 years
    @AnderBiguri: here are some tests you could run to compare: gist.github.com/amroamroamro/e66ac6a88b0692d995fd