Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

matrix

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

like image 442
CyberPlayerOne Avatar asked Apr 12 '14 15:04

CyberPlayerOne


People also ask

How do you know if two matrices are the same?

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.

What is matrix Isequal?

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 .

How do you know if two matrices are similar NumPy?

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.


1 Answers

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.

like image 128
flodel Avatar answered Oct 27 '22 08:10

flodel