Is there a built in MATLAB function to find out if a matrix contains a certain value?
(ala PHP's in_array()
)
This question is related to
matlab
function
matrix
floating-point
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
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)
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
Source: Stackoverflow.com