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)?
SparseArray[Normal[assoc]]
or (if you know the dimensions in advance)SparseArray[Normal[assoc],{3,3}]
. $\endgroup$SparseArray[Keys[assoc] -> Values[assoc], {3, 3}]
should perform better for long assiciations. $\endgroup$SparseArray[KeyValueMap[Rule, assoc]]
would work too. $\endgroup$