# Passing list into another list

Suppose I have a zero matrix Amat and a list of values ltest that contains the values of the matrix Amat for the some of its diagonal elements:

L = 10000;
Amat = 0. IdentityMatrix[L];
ltest = {{-0.70710, 1329}, {-0.25, 5607}, {-0.3535, 1261}, {-0.25, 4393}, {-0.5, 4358},
{-0.3511, 1009}, {-1., 3815}, {-0.25, 3784}, {-0.133, 3667}, {-0.88, 909}};


Now in order to pass the second column of ltest to Amat I can do:

For[i = 1, i <= Length[ltest], i++, Amat[[ltest[[All, 2]][[i]], ltest[[All, 2]][[i]]]] = ltest[[All, 1]][[i]]]


Is there a shorter way without using For?

• Have you already tried looking at SparseArray[]? – J. M.'s ennui Jan 26 at 12:18

## 2 Answers

L = 10000;
ltest = {{-0.70710, 1329}, {-0.25, 5607}, {-0.3535, 1261}, {-0.25,
4393}, {-0.5, 4358}, {-0.3511, 1009}, {-1., 3815}, {-0.25,
3784}, {-0.133, 3667}, {-0.88, 909}};
Amat = SparseArray[{#2, #2} -> #1 & @@@ ltest, {L, L}, 0]


And Amat can be used as an ordinary matrix.

• thanks for the answer! – geom Jan 26 at 13:05
• Shouldn't it be Amat = SparseArray[{#[], #[]} -> #[] & /@ ltest, {L, L}, 0]? – MelaGo Jan 26 at 13:28
• @MelaGo Yes you are right.@SneezeFor16Min please edit your post – geom Jan 26 at 14:01
• @MelaGo Thanks for pointing that out! I misread OP's code... Answer updated. – SneezeFor16Min Jan 26 at 15:44

With L and ltest as given in the OP, here is another way to use SparseArray[]:

DiagonalMatrix[SparseArray[Rule @@@ Reverse[ltest, 2], L]]


DiagonalMatrix[] is smart enough to return a SparseArray[] when fed a diagonal represented as a SparseArray[].

• Smart! This is ~1.6x faster than using straight-forward Rules for reasons I don't know. – SneezeFor16Min Jan 26 at 17:11
• can it be used if the elements of Amat are not diagonal, i.e ltest = {{-0.70710, 5, 1329}, {-0.25, 31,5607}, {-0.3535, 411,1261}, {-0.25,706, 4393}, {-0.5,58, 4358}, {-0.3511, 2871,1009}, {-1.,7415, 3815}, {-0.25,1254, 3784}, {-0.133, 33,3667}, {-0.88, 17,909}}; where the last two elements are the i,j indices of Amat? – geom Jan 26 at 17:45
• @geom, then you use SparseArray[] directly, as I originally advised you in my comment to your question. Try it out, and if you get stuck, ask a new question. – J. M.'s ennui Jan 26 at 17:56
• @J.M. thanks, no need to ask a new question, SparseArray[] works fine – geom Jan 26 at 18:03