在 Matlab 中比较两个矩阵
我有两个矩阵 x 和 y,它们都是来自不同算法/例程的结果,这些算法/例程应该计算相同的结果。 虽然我知道 isequal() 会检查 x 和 y 是否是相同的矩阵,但这些矩阵中的条目不会完全相同(即,在最坏的情况下,某些条目可能有 5% 的折扣)。 在这种情况下,比较它们以查看它们是否足够接近以被视为相同结果的最佳方法是什么? 预先感谢您的建议。
I have two matrices x and y, both are results from different algorithms/routines that are supposed to calculate the same result. While I know that the isequal() would check if x and y are the same matrix, the entries in those matrices would not be exactly the same (i.e. some entries may be with 5% off in worst case scenario). In this scenario, what would be the best method of comparing them to see if they are close enough to be considered the same result? Thanks in advance for the advices.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
试试这个:
这将返回一个逻辑矩阵,如果 A 和 B 相对于 B 的相对差异小于 5%,则该矩阵对于每个元素都为 true。
如果你想问这些是否都成立(都满足上述条件):
Try this:
This will return a logical matrix which will be true for each element if the relative difference between A and B with respect to B is less than 5 percent.
If you want to ask if all of these are true (they all satisfy the above condition):
修改Edric的解决方案:
变量相同如果任何元素的绝对误差或相对误差大于您选择的容差,则为 false。 另外,如果 x 的任何元素恰好为 0,那么 relError 的某些元素最终可能是无限的或不是数字,所以我使用ISFINITE 函数通过设置忽略这些值到 0。
我不建议使用 IMAGESC比较绘图,因为 1)数据在显示时会缩放,2)显示的颜色图具有离散数量的颜色值(我认为默认情况下是 256,因此有很多舍入),以及 3)细微的变化从两个图的视觉比较中,颜色可能并不那么明显。
Modifying Edric's solution:
The variable same will be false if either the absolute or the relative error of any element is larger than whatever tolerances you choose. Also, if any elements of x happen to be exactly 0, then some of the elements of relError could end up being either infinite or not-a-number, so I used the ISFINITE function to ignore those values by setting them to 0.
I wouldn't suggest using IMAGESC to compare plots, since 1) the data is scaled when it is displayed, 2) the colormap for the display has a discrete number of color values (which I think is 256 by default, hence lots of rounding), and 3) subtle variations in color may not be all that apparent from visual comparison of two plots.
我会考虑以绝对容差和相对容差来做这样的事情:
I would consider doing something like this with an absolute tolerance as well as a relative tolerance:
当 x 和 y 中有非常小的值对时,结果将返回 0,尽管这些值本身可以忽略。 对已接受解决方案的补充
因此,可以使用 来丢弃非常小的错误。 因此,这些值不考虑相对误差。
When you have very small value pairs in x and y, the result would return 0 although the values are ignorable themselves. So, an addition to the accepted solution
might be used to discard very small errors. Thus, the relative error is not considered for these values.
对于包含浮点值的矩阵 x 和 y,您可以检查数组元素是否在彼此给定的容差范围内。
示例代码:
For matrices x and y containing floating point values, you may check if array elements are within a given tolerance of one another.
Sample code:
使用 'isequal(a,b),其中 a 和 b 是两个矩阵,如果 1 则为 true
make use of 'isequal(a,b) where a and b are two matrices, if 1 it is true