0

I got a problem about checking if two matrices are equal in MATLAB.

Specifically, I want to verify if, for a matrix W, all elements are equal to each other and all row sums are equal to 1 we would have W = W^2.

Therefore I wrote the following code which aims to check if every element of these two matrices are equivalent, to conclude whether the matrices are equal to each other. But it turns out that this does not work since the W8 matrix should be equal to its square.

for i = 1 :60
    for j = 1 :60
        if(W8(i,j) - W8_square(i,j) ~= 0)
            disp('the matrix are not equal');
            break;
        end
    end
end
Wolfie
  • 27,562
  • 7
  • 28
  • 55
C.Deng
  • 1
  • 1
  • 4
    Are you having this problem: https://stackoverflow.com/questions/686439/why-is-24-0000-not-equal-to-24-0000-in-matlab ? It looks like you are – Ander Biguri Apr 01 '19 at 10:52

1 Answers1

1

There is a matlab function for it: eq = isequal(W8,W8_square) should work Here you find the reference https://www.mathworks.com/help/matlab/ref/isequal.html Be careful that if this checks for EXACT identity, so computation errors, of the order of eps, may affect the result. To solve this, I would subtract the two matrixes and check the norm of the result: below a certain threshold (low) they are equal. Here you have an example code for your problem:

n = 10; %matrix size
W8 = ones(n)/n; %Generating W8
W8_square = W8^2; 
eq = isequal(W8,W8_square) %checking EXACT identity
M_difference = W8-W8_square; %Difference matrix
eq2 = isequal(M_difference<=eps,ones(n)) %%comparing every value with eps
enrico_ay
  • 76
  • 6
  • 1
    You'd be better of elaborating on your comment about checking norms, since the `isequal` solution will have the same result as the OP. That said, the floating point comparison question is a duplicate of [this one](https://stackoverflow.com/questions/686439/why-is-24-0000-not-equal-to-24-0000-in-matlab), so you're better spending your time on the next question :) – Wolfie Apr 01 '19 at 13:17