# Add 1 to diagonal elements of a matrix

I have a list of lists of numbers, for example:

{{1, 1, 1, 1}, {1, 1, 1, 1}, {1, 1, 1, 1}, {1, 1, 1, 1}}


The length of the list is the same length of each sublist. What I want to achieve is to add plus 1 to the diagonal elements without using For. Given the list above as an input, I need a result like this:

{{2, 1, 1, 1}, {1, 2, 1, 1}, {1, 1, 2, 1}, {1, 1, 1, 2}}


Thank you.

• Why not list + IdentityMatrix@Length@list? Sep 19, 2017 at 4:28
• It works great, thank you! Sep 19, 2017 at 4:48
• @Simon, looks like an answer to me. ;) Sep 19, 2017 at 5:33
• Next time if you cross-post, please link the two posts together. Sep 19, 2017 at 8:08
• @SimonRochester Hei man,that is a good answerr. :)
– yode
Sep 19, 2017 at 8:25

By popular demand:

list + IdentityMatrix@Length@list


I'm a big fan of IdentityMatrix -- I try to use it whenever possible.

Using some undocumented functionality,

m = {{1, 1, 1, 1}, {1, 1, 1, 1}, {1, 1, 1, 1}, {1, 1, 1, 1}};
diag = ConstantArray[1, Length[m]];

LinearAlgebraAddVectorToMatrixDiagonal[m, diag]
{{2, 1, 1, 1}, {1, 2, 1, 1}, {1, 1, 2, 1}, {1, 1, 1, 2}}


For 11.2, use LinearAlgebraPrivateAddVectorToMatrixDiagonal[] instead.

• why this dosn't work anymore!? Mar 28, 2019 at 17:26
• In which version? Mar 28, 2019 at 17:30
• 10.4.1. Check my new Question please! Mar 28, 2019 at 17:32

I am hoping that Table is ok with you !

In:= list = {{1, 1, 1, 1}, {1, 1, 1, 1}, {1, 1, 1, 1}, {1, 1, 1, 1}}

Table[list[[i, i]] = list[[i, i]] + 1, {i, 1, Length[list]}];

In:= list

Out= {{2, 1, 1, 1}, {1, 2, 1, 1}, {1, 1, 2, 1}, {1, 1, 1, 2}}

• Table[list[[i, i]]++, {i, 1, Length[list]}]; ;-) Sep 19, 2017 at 9:44
m = {{1, 1, 1, 1}, {1, 1, 1, 1}, {1, 1, 1, 1}, {1, 1, 1, 1}};
mnew = ReplacePart[m, {i_, i_} :> m[[i, i]] + 1]
`