3
$\begingroup$

Imagine I have the following association, where the keys are given as pairs of natural numbers

assoc = <|{1, 1} -> 0, {2, 1} -> 1, {1, 3} -> 0, {3, 2} -> 0, {1, 2} -> 1, {3, 1} -> 0,
    {2, 3} -> 0, {3, 3} -> 1, {2, 2} -> 0|>

To get the connectivity matrix defined by this association, where in {i, j}, i is the row and j is the column, I can do

Partition[Values@KeySort@assoc, 3]
Out[]= {{0, 1, 0}, {1, 0, 0}, {0, 0, 1}}

Is there a faster way to directly get the previous matrix (or list of lists)?

$\endgroup$
3
  • $\begingroup$ Try SparseArray[Normal[assoc]] or (if you know the dimensions in advance) SparseArray[Normal[assoc],{3,3}]. $\endgroup$ Sep 17 at 19:45
  • 5
    $\begingroup$ Thinking of it, SparseArray[Keys[assoc] -> Values[assoc], {3, 3}] should perform better for long assiciations. $\endgroup$ Sep 17 at 19:47
  • 1
    $\begingroup$ SparseArray[KeyValueMap[Rule, assoc]] would work too. $\endgroup$
    – Roman
    Sep 19 at 12:50
1
$\begingroup$
nodes = Union@Catenate@Keys@assoc
edges = Cases[Normal@assoc, ({x_, y_} -> 1) :> x -> y]
AdjacencyMatrix@Graph[nodes, edges]  (* a SparseArray *)
$\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.