[Solved] function for matrix


I’ve tried this, looking at wikipedia.
http://en.wikipedia.org/wiki/Invertible_matrix#Blockwise_inversion

getInverse <- function(mat) {

  if(nrow(mat) == 1)
  {
    return (matrix( 1.0/ mat[1,1] ))
  }

  idx <- nrow(mat) / 2
  A <- mat[1:idx, 1:idx, drop=F]
  B <- mat[1:idx, -1:-idx, drop=F]
  C <- mat[-1:-idx, 1:idx, drop=F]
  D <- mat[-1:-idx, -1:-idx, drop=F]

  invA <- getInverse(A)
  temp <- getInverse(D - C %*% invA %*% B)
  element11 <- invA + invA %*% B %*% temp %*% C %*% invA
  element12 <- -invA %*% B %*% temp
  element21 <- -temp %*% C %*% invA
  element22 <- temp

  result <- cbind(rbind(element11, element21), rbind(element12, element22))
}

set.seed(1)
mat <- matrix(rnorm(9), nrow=3)
print("Function test:")
print(getInverse(mat))
print("Using Solve:")
solve(mat)

Update for the question in the comments:
I’ve chosen these names to match the 4 different elements, or blocks, on the wiki page block matrix inversion formula. I see the result as a matrix of matrices, thus element11 was chosen for row 1, column 1 and element21 for row 2, element 1. I didn’t really ‘work out’ anything I just stored some intermediate calculations into variables. Finally, the result is built by combining the blocks.

4

solved function for matrix