8
$\begingroup$

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!

$\endgroup$
0

5 Answers 5

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

$\endgroup$
3
$\begingroup$
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

enter image description here

$\endgroup$
3
$\begingroup$
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}}*)
$\endgroup$
2
$\begingroup$
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
  }

enter image description here

$\endgroup$
1
$\begingroup$

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)

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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