# 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? – Simon Rochester Sep 19 '17 at 4:28
• It works great, thank you! – Gabriela Sep 19 '17 at 4:48
• @Simon, looks like an answer to me. ;) – J. M. is away Sep 19 '17 at 5:33
• Next time if you cross-post, please link the two posts together. – Szabolcs Sep 19 '17 at 8:08
• @SimonRochester Hei man,that is a good answerr. :) – yode Sep 19 '17 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!? – Alrubaie Mar 28 at 17:26
• In which version? – J. M. is away Mar 28 at 17:30
• 10.4.1. Check my new Question please! – Alrubaie Mar 28 at 17:32

I am hoping that Table is ok with you !

In[1]:= 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[3]:= list

Out[3]= {{2, 1, 1, 1}, {1, 2, 1, 1}, {1, 1, 2, 1}, {1, 1, 1, 2}}

• Table[list[[i, i]]++, {i, 1, Length[list]}]; ;-) – AccidentalFourierTransform Sep 19 '17 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]
`