# Adding lists to specific elements in a list

I have compiled lists of non-diagonal and diagonal entries for a matrix. I'm trying to add elements from the diagonal-entry lists into certain entries of the non-diagonal lists. Is there a feasible way I can add these lists without retyping everything up in a new list? Or should I just try another approach?

I've listed examples of my lists in a much shortened version for simplicity; in reality, I'm trying to create a matrix of size 30x30. I've tried messing around with the Part[] function, but haven't been able to get it to work the way I desire.

non-diags = {{0,0,-1},{0,0,-1},{-1,-1,0}}
diags = {5,4,6}


My desired list is:

matrixlist = {{5,0,-1},{0,4,-1},{-1,-1,6}}


Thanks for any help with this!

nondiags = {{0, 0, -1}, {0, 0, -1}, {-1, -1, 0}};
diags = {5, 4, 6};
DiagonalMatrix[diags] + nondiags


m = {{0, 0, -1}, {0, 0, -1}, {-1, -1, 0}};

d = {5, 4, 6};


Using SubsetMap (new in 12.0)

SubsetMap[d &, m, Table[{i, i}, {i, Length @ d}]] // MatrixForm


m = {{0, 0, -1}, {0, 0, -1}, {-1, -1, 0}};

d = {5, 4, 6};


Using ReplacePart:

ReplacePart[m, {i_, i_} :> d[[i]]]

(*{{5, 0, -1}, {0, 4, -1}, {-1, -1, 6}}*)

Clear["Global*"];
nondiags = {{0, 0, -1}, {0, 0, -1}, {-1, -1, 0}};
diags = {5, 4, 6};

res = MapIndexed[ReplacePart[#1, First@#2 -> diags[[First@#2]]] &,
nondiags]


OR

rules = Thread[Table[{i, i}, {i, Length@diags}] -> diags]
ReplacePart[nondiags, rules]


(* same result *)

Visualization:

MatrixForm /@ {
diags
, nondiags
, res
}


To replace the diagonal of a square matrix with a vector:

MapThread[ReplacePart, {nondiags, diags, Range[Length@diags]}]

(* {{5, 0, -1}, {0, 4, -1}, {-1, -1, 6}} *)
`

(Learned from Leonid Shifrin's book, Mathematica An Advanced Introduction, pp 269-270, available at the Internet Archive, among many other places)