如何比较两个数组的所有元素?
我有两个大约 1000 行和 1000 列的大数组。我需要比较这些数组的每个元素,如果相应的元素相等,则将 1 存储在另一个数组中。
我可以用 for 循环来做到这一点,但这需要很长时间。我怎样才能更快地做到这一点?
I have two big arrays with about 1000 rows and 1000 columns. I need to compare each element of these arrays and store 1 in another array if the corresponding elements are equal.
I can do this with for loops but that takes a long time. How can I do this faster?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
给出的答案都是正确的。我只是想详细说明gnovice的评论关于浮点测试。
比较浮点数是否相等时,需要使用容差值。常用的公差比较有两种:绝对公差和相对公差。 (来源)
绝对容差
a
和b
的比较如下所示:相对容差比较如下所示:
您可以将上述两个函数实现为匿名函数:
然后您可以将它们用作:
The answers given are all correct. I just wanted to elaborate on gnovice's remark about floating-point testing.
When comparing floating-point numbers for equality, it is necessary to use a tolerance value. Two types of tolerance comparisons are commonly used: absolute tolerance and relative tolerance. (source)
An absolute tolerance comparison of
a
andb
looks like:A relative tolerance comparison looks like:
You can implement the above two as anonymous functions:
Then you can use them as:
如果您的两个矩阵
A
和B
大小相同,那么您可以这样做:并且
index
将是 逻辑数组,其中 1 处处都是A
的元素和B
相等且为零。警告...
如果
A
和B
包含整数,上面的应该没问题。但是,如果它们包含浮点值,您可能会得到不需要的结果。对于完全相等的元素,上面的代码只会有值1。即使是最小的差异也会导致元素被视为不相等。您可以查看此问题的答案 有关处理“浮点运算的危险”的更多信息。一种解决方案是检查数组元素是否在彼此给定的容差范围内,如下所示:
上面将为您提供一个逻辑数组
index
,其中A
和B
彼此相差在 0.0001 以内,否则为零。If your two matrices
A
andB
are the same size, then you can do this:and
index
will be a logical array with ones everywhere an element ofA
andB
are equal and zero otherwise.A word of warning...
If
A
andB
contain integers, the above should be fine. However, if they contain floating point values, you may get undesired results. The above code will only have values of one for elements that are exactly equal. Even the smallest difference will cause the elements to be considered unequal.You can look at this question's answers for more information about dealing with the "perils of floating point operations". One solution would be to check that array elements are within a given tolerance of one another, like so:
The above will give you a logical array
index
with ones everywhere the elements ofA
andB
are within 0.0001 of each other and zero otherwise.只需使用普通的
==
运算符即可:Just use the normal
==
operator: