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

查看:339
本文介绍了在Matlab中比较两个矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个矩阵x和y,都是来自不同算法/例程的结果,它们应该计算相同的结果。虽然我知道等号()将检查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's 解决方案:

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天全站免登陆