如何比较两个数组的所有元素? [英] How do I compare all elements of two arrays?
问题描述
我有两个大数组,大约有1000行和1000列。我需要比较这些数组的每个元素,如果相应的元素相等,将另一个数组存储1。
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.
我可以用for循环,但是需要很长时间。
I can do this with for loops but that takes a long time. How can I do this faster?
推荐答案
提供的答案都是正确的。我只想详细说明 gnovice的说明关于浮点测试。
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)
a
和 b
的绝对容差比较如下: / p>
An absolute tolerance comparison of a
and b
looks like:
|a-b| < tol
相对公差比较如下:
|a-b| < tol*max(|a|,|b|) + tol_floor
匿名函数:
%# absolute tolerance equality
isequalAbs = @(x,y,tol) ( abs(x-y) <= tol );
%# relative tolerance equality
isequalRel = @(x,y,tol) ( abs(x-y) <= ( tol*max(abs(x),abs(y)) + eps) );
然后您可以使用它们:
%# let x and y be scalars/vectors/matrices of same size
x == y
isequalAbs(x, y, 1e-6)
isequalRel(x, y, 1e-6)
这篇关于如何比较两个数组的所有元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!