フィルターのクリア

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 Center および File ExchangeMatrix Indexing についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by