Reputation: 107
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?
Upvotes: 2
Views: 1802
Reputation: 12937
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.
Upvotes: 0
Reputation: 206242
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
Upvotes: 4