6
$\begingroup$

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.

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

4 Answers 4

13
$\begingroup$

By popular demand:

list + IdentityMatrix@Length@list

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

$\endgroup$
4
$\begingroup$

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]];

LinearAlgebra`AddVectorToMatrixDiagonal[m, diag]
   {{2, 1, 1, 1}, {1, 2, 1, 1}, {1, 1, 2, 1}, {1, 1, 1, 2}}

For 11.2, use LinearAlgebra`Private`AddVectorToMatrixDiagonal[] instead.

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

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}}
$\endgroup$
1
1
$\begingroup$
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]
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.