简体   繁体   中英

Adding elements to the diagonal of a matrix that is not square in R

I want to be able to add a value (in my code nug ) to the i,j entry of a matrix where i = j (so like a Kronecker delta function). Its very easy to do when the matrix is square (see my code below) however I am not sure how to do it in one line when the matrix is not square

nug = 2
R = tau + diag(nug,nrow(tau))

The above code works when tau is a square matrix but now imagine that tau is not square. How would I add nug to each of the i,j elements of tau where i = j?

m <- matrix(1:6, ncol = 2)
m
     [,1] [,2]
[1,]    1    4
[2,]    2    5
[3,]    3    6
diag(m) <- diag(m) + 1:2
m
     [,1] [,2]
[1,]    2    4
[2,]    2    7
[3,]    3    6

You can do this :

m[col(m)==row(m)] <- m[col(m)==row(m)] +nug 

Using a matrix of zeros to show this:

m <- matrix(rep(0,6), ncol = 2)
> m[col(m)==row(m)] <- m[col(m)==row(m)] +2
> m
     [,1] [,2]
[1,]    2    0
[2,]    0    2
[3,]    0    0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM