Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inverse of matrix in R

People also ask

How do you do inverse in R?

The inverse of a matrix can be calculated in R with the help of solve function, most of the times people who don't use R frequently mistakenly use inv function for this purpose but there is no function called inv in base R to find the inverse of a matrix.

Which command is used to get a inverse of the matrix A in R?

Finding Inverse of a Matrix in R Programming – inv() Function. inv() function in R Language is used to calculate inverse of a matrix.

How do you find the inverse of a 2x2 matrix?

To find the inverse of a 2x2 matrix: swap the positions of a and d, put negatives in front of b and c, and divide everything by the determinant (ad-bc).


solve(c) does give the correct inverse. The issue with your code is that you are using the wrong operator for matrix multiplication. You should use solve(c) %*% c to invoke matrix multiplication in R.

R performs element by element multiplication when you invoke solve(c) * c.


You can use the function ginv() (Moore-Penrose generalized inverse) in the MASS package


Note that if you care about speed and do not need to worry about singularities, solve() should be preferred to ginv() because it is much faster, as you can check:

require(MASS)
mat <- matrix(rnorm(1e6),nrow=1e3,ncol=1e3)

t0 <- proc.time()
inv0 <- ginv(mat)
proc.time() - t0 

t1 <- proc.time()
inv1 <- solve(mat)
proc.time() - t1