简体   繁体   中英

Adding a value to each element of a matrix diagonal in R

I have a matrix:

1 2 3
5 6 10
8 3 5

I want to add a value (say 2) to each element of the diagonal:

3 2 3    
5 8 10
8 3 7

How should I do it?

With your sample data

m<-matrix(scan(text="1 2 3
5 6 10
8 3 5"), ncol=3)

You can use the diag() function to both extract and update the diagonal elements of your matrix

diag(m) <- diag(m)+2
m

Although diag function is the best for this purpose, this is just another way around:

d <- row(m)-col(m)==0
m[d] <- m[d]+2

d is a logical matrix in which only diagonal elements are TRUE.

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