Error in comparing equal matrices

2 次查看(过去 30 天)
I am trying to display a success message if the code identifies two matrices which are equal, but I see that it works out only for a few elements of the matrices. Can anyone please correct me if wrong? Here is my code below:
Rotation_matrix = rotm2tform([0.9254 0.0180 0.3785; 0.1632 0.8826 -0.4410; -0.3420 0.4698 0.8138])
res = rpy2tr(30*pi/180,20*pi/180,10*pi/180)
if size(Rotation_matrix==res)
for i=1:size(Rotation_matrix)
for j=1:size(Rotation_matrix)
if Rotation_matrix(i,j)==res(i,j)
disp("success")
else
disp("fail")
end
end
end
else
disp("Sizes are not equal")
end

采纳的回答

Voss
Voss 2021-12-28
It looks like you are trying to loop over both dimensions of two matrices and compare the elements one at a time, and first you check that the sizes are the same. This is how you would do that:
if isequal(size(Rotation_matrix),size(res))
for i=1:size(Rotation_matrix,1)
for j=1:size(Rotation_matrix,2)
if Rotation_matrix(i,j)==res(i,j)
disp("success")
else
disp("fail")
end
end
end
else
disp("Sizes are not equal")
end
But notice that you can stop checking as soon as you know one element is not the same, if all you need is to know whether the matrices are the same:
if isequal(size(Rotation_matrix),size(res))
found_a_difference = false;
for i=1:size(Rotation_matrix,1)
for j=1:size(Rotation_matrix,2)
if Rotation_matrix(i,j)==res(i,j)
disp("success")
else
disp("fail")
found_a_difference = true;
break
end
end
if found_a_difference
break
end
end
else
disp("Sizes are not equal")
end
Or, a better and simpler solution to the entire problem of comparing two matrices is just to use isequal once (if you don't care about which element(s) are different):
if isequal(Rotation_matrix,res)
disp('matrices are the same');
else
disp('matrices are different');
end
  2 个评论
DGM
DGM 2021-12-28
Considering that this is all probably done in floats, it might be worth using a tolerance
tol = 1E-12; % or something
if all(abs(Rotation_matrix - res) <= tol)
disp('matrices are the same');
else
disp('matrices are different');
end
N/A
N/A 2021-12-28
Hi, thanks a lot for this. I tried the isequal() method several times (because that is the most suggested), but it does not work unfortunately. It still displays "matrices are different". I used the tolerance as 0.0001 and it works. Really appreciate your help.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by