1
$\begingroup$

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?

$\endgroup$
1
  • 3
    $\begingroup$ Have you already tried looking at SparseArray[]? $\endgroup$ – J. M.'s ennui Jan 26 at 12:18
3
$\begingroup$
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.

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

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[].

$\endgroup$
4
  • $\begingroup$ Smart! This is ~1.6x faster than using straight-forward Rules for reasons I don't know. $\endgroup$ – SneezeFor16Min Jan 26 at 17:11
  • $\begingroup$ 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? $\endgroup$ – geom Jan 26 at 17:45
  • $\begingroup$ @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. $\endgroup$ – J. M.'s ennui Jan 26 at 17:56
  • $\begingroup$ @J.M. thanks, no need to ask a new question, SparseArray[] works fine $\endgroup$ – geom Jan 26 at 18:03

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.