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
Two matrices are equal if all three of the following conditions are met: Each matrix has the same number of rows. Each matrix has the same number of columns. Corresponding elements within each matrix are equal.
Two matrices are said to be equal if: Both the matrices are of the same order i.e., they have the same number of rows and columns A m × n = B m × n . If the elements of the first matrix are equal to the corresponding elements in the second matrix a i j = b i j .
To check if two NumPy arrays A and B are equal: Use a comparison operator (==) to form a comparison array. Check if all the elements in the comparison array are True.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With