Borrar filtros
Borrar filtros

Error in comparing equal matrices

2 visualizaciones (últimos 30 días)
N/A
N/A el 28 de Dic. de 2021
Comentada: N/A el 28 de Dic. de 2021
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

Respuesta aceptada

Voss
Voss el 28 de Dic. de 2021
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 comentarios
DGM
DGM el 28 de Dic. de 2021
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 el 28 de Dic. de 2021
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.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Matrix Indexing en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by