Adam Majdi Adam Majdi - 2 months ago 16
R Question

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?

Answer

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
Comments