필터 지우기
필터 지우기

Error in comparing equal matrices

조회 수: 2 (최근 30일)
N/A
N/A 2021년 12월 28일
댓글: N/A 2021년 12월 28일
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