Function for 'does matrix contain value X?'

前端 未结 4 2062
天命终不由人
天命终不由人 2020-12-05 09:04

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

4条回答
  •  -上瘾入骨i
    2020-12-05 09:50

    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
    

提交回复
热议问题