Adam Majdi - 9 months ago 100

R Question

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
```

Source (Stackoverflow)