R – How to compare two matrices to see if they are identical in R

matrixr

For example, I have two matrices and I wanna know if they are identical in each element.

mymatrix<-Matrix(rnorm(20),ncol=5)
mysvd<-svd(mymatrix) 
newmatrix<-mysvd$u %*% diag(mysvd$d) %*% t(mysvd$v)

I used the following ways to compare them:

identical(Matrix(newmatrix), mymatrix)
all.equal(Matrix(newmatrix), mymatrix)

Why the first one doesn't return TRUE?
No matter I use Matrix from the matrix package or the matrix from base package

Best Answer

They are not exactly equal (per identical) because of very small differences:

> max(abs(Matrix(newmatrix) - mymatrix))
[1] 1.110223e-15

but these differences are smaller than the default tolerance inside all.equal:

> .Machine$double.eps ^ 0.5
[1] 1.490116e-08

so identical will return FALSE and all.equal will return TRUE.

Related Topic