Comparing two matrix in Matlab
3 次查看(过去 30 天)
显示 更早的评论
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.
1 个评论
Anuj Kumar
2020-12-24
you can try this,assumming x and y has same dimensions
len=lenght(x);
tolerance=x-y;
check=tolerance<0.001;
sum_Check=sum(check)
if sum_Check==len %then results can be accepted
回答(2 个)
Titus Edelhofer
2014-6-26
Hi,
this question is rather tricky to answer in general. A simple approach is to compute the relative error. That works fine as long as there are no zeros in it, i.e.,
absError = abs(A-B);
relError = max(absError(:) ./ abs(A(:)));
This also assumes, that A and B are at least comparable in size, so it does not make a difference if you devide by A or B.
Taking care of all eventualities (NaN, inf, zeros ...) makes it more difficult to answer.
Titus
Anastasios
2014-6-26
I assume you have some floating point variables, in order to have this 5% error. Try to define a function to check if they are relatively equal, such as
function test = isequalRel(x,y,tol);
test = ( abs(x-y) <= ( tol*max(abs(x),abs(y)) + eps) );
if (! test)
printf("fail x=%e y=%e tol=%e\n", x, y, tol);
end
So basically you do the following :
|a-b| < tol*max(|a|,|b|) + tol_floor
3 个评论
Anastasios
2014-6-26
Use the following command
abs(A-B) <= ( tol*max(abs(A),abs(B)) + eps)
where the tol = 0.005 (5%) You will get a logical answer if they are within this error of 5% the answer would be 1 otherwise 0.
Hope it helps
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!