在 Matlab 中比较两个矩阵 [英] Comparing two matrices in Matlab

查看:88
本文介绍了在 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.

推荐答案

修改 Edric 的解决方案:

absTol = 1e-3;   % You choose this value to be what you want!
relTol = 0.05;   % This one too!
absError = x(:)-y(:);
relError = absError./x(:);
relError(~isfinite(relError)) = 0;   % Sets Inf and NaN to 0
same = all( (abs(absError) < absTol) & (abs(relError) < relTol) );

如果绝对任何元素的相对误差大于您选择的任何容差,则变量相同将为假.此外,如果 x 的任何元素恰好是 0,那么 relError 的某些元素最终可能是无限的或不是数字,所以我使用ISFINITE 函数通过设置它们来忽略这些值到 0.

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.

我不建议使用 IMAGESC比较图,因为 1) 数据在显示时被缩放,2) 显示的颜色图具有离散数量的颜色值(我认为默认情况下是 256,因此有很多四舍五入),以及 3) 细微的变化从两个图的视觉比较来看,颜色可能并不那么明显.

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.

这篇关于在 Matlab 中比较两个矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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