“矩阵是否包含值 X"的函数 [英] Function for 'does matrix contain value X?'

查看:20
本文介绍了“矩阵是否包含值 X"的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有内置的 MATLAB 函数来确定矩阵是否包含某个值?(ala PHP 的 in_array())

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

推荐答案

有很多方法可以做到这一点.ismember 是第一个想到的,因为它是您希望采取的一组成员资格操作.于是

Many ways to do this. ismember is the first that comes to mind, since it is a set membership action you wish to take. Thus

X = primes(20);
ismember([15 17],X)
ans =
      0    1

由于 15 不是素数,而 17 是素数,因此 ismember 在这里做得很好.

Since 15 is not prime, but 17 is, ismember has done its job well here.

当然,find(或任何)也可以.但是这些不是从 ismember 的意义上矢量化的.我们可以测试 15 是否在由 X 表示的集合中,但是测试这两个数字需要循环或连续测试.

Of course, find (or any) will also work. But these are not vectorized in the sense that ismember was. We can test to see if 15 is in the set represented by X, but to test both of those numbers will take a loop, or successive tests.

~isempty(find(X == 15))
~isempty(find(X == 17))

或者,

any(X == 15)
any(X == 17)

最后,我要指出,如果数字可能是真正的浮点数,则对精确值的测试是危险的.正如我所展示的,针对整数值的测试很容易.但是针对浮点数的测试通常应该采用容差.

Finally, I would point out that tests for exact values are dangerous if the numbers may be true floats. Tests against integer values as I have shown are easy. But tests against floating point numbers should usually employ a tolerance.

tol = 10*eps;
any(abs(X - 3.1415926535897932384) <= tol)

这篇关于“矩阵是否包含值 X"的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆