# [R] extracting the diagonal of an inverse matrix

Camarda, Carlo Giovanni Camarda at demogr.mpg.de
Mon Apr 22 10:51:25 CEST 2013

```Dear Greg,

thanks a lot for your prompt reply. I was aware of the link and the associated papers.
In my previous mail I was wondering whether there was already an R-routine for coping with this issue.

I add below a testable example which reproduces my problem.

Thanks again,
Giancarlo

## dimensions (my actual dimensions are much larger and I use sparse matrices)
m <- 3
n <- 3
## building A
## diagonal part
d <- 1:(m*n)
D <- diag(d)
## additional ~dense part (:penalty term)
P1 <- diff(diag(m), diff=2)
P2 <- diff(diag(n), diff=2)
P1a <- kronecker(diag(n), t(P1)%*%P1)
P2a <- kronecker(t(P2)%*%P2, diag(m))
P <- 1000 * P1a + 1000 * P2a
## final matrix A
A <- D + P
## solving A
B <- solve(A)
## what I just actually need
diag(B)

________________________________________
From: Greg Snow [538280 a gmail.com]
Sent: Saturday, April 20, 2013 12:16 AM
To: Camarda, Carlo Giovanni
Cc: r-help a stat.math.ethz.ch
Subject: Re: [R] extracting the diagonal of an inverse matrix

This link http://math.stackexchange.com/questions/18488/diagonal-of-an-inverse-of-a-sparse-matrix might help.  It is about sparse matrices, but the general idea should be able to be extended to non-sparse matrices as well.

On Fri, Apr 19, 2013 at 8:13 AM, Camarda, Carlo Giovanni <Camarda a demogr.mpg.de<mailto:Camarda a demogr.mpg.de>> wrote:
Dear R-users,

I would like to know whether there is a way to extract a diagonal of an inverse matrix without computing the inverse of the matrix itself. The size of my matrices are really huge and, also using sparse matrix, computing the inverse leads to storage problems and low speed.

In other words, given a square matrix A, I aim to know diag(B), where B=solve(A), without computing solve(A).

Accidentally (I do not know whether it helps), I could write the matrix A as follows:
A <- D + P
where D is a diagonal matrix.

I read there are methods around, but, before implementing one of them by myself, could you please inform whether there is already an R-routine for this issue?