# How can I create SparseArray by imposing conditions?

I have two lists: one for directed links list1 and another list2 for the values associated with the links.

list1 = {{1 \[DirectedEdge] 4}, {3 \[DirectedEdge] 2, 1 \[DirectedEdge]
3, 2 \[DirectedEdge] 4}};

list2 = {{0.1}, {0.4, 0.7, 0.9}};


I want to create two SparseArrays of size (10,10). One for a single link,

{1 \[DirectedEdge] 4}


with the associated value of 0.1. Another SparseArray of the same size for three links:

{3 \[DirectedEdge] 2, 1 \[DirectedEdge]3, 2 \[DirectedEdge] 4}


with the associated values in

{0.4, 0.7, 0.9}.

• Did you want something like PadRight[WeightedAdjacencyMatrix[Graph[{3 \[DirectedEdge] 2, 1 \[DirectedEdge] 3, 2 \[DirectedEdge] 4}, EdgeWeight -> {0.4, 0.7, 0.9}]], {10, 10}]? Commented Nov 13, 2019 at 23:44
• @J.M. will be back soon: Not quite. EdgeWeights are misplaced. DirectedGraph has links following matrix index (row->column). In your answer, the placement of weights is not what I wanted. Commented Nov 13, 2019 at 23:52
• OK, then does PadRight[WeightedAdjacencyMatrix[Graph[Range[3], {3 \[DirectedEdge] 2, 1 \[DirectedEdge] 3, 2 \[DirectedEdge] 4}, EdgeWeight -> {0.4, 0.7, 0.9}]], {10, 10}] do what you want? Commented Nov 13, 2019 at 23:55
• @J.M. will be back soon: Now it works fine. In my example, I had two separate directed graphs with specific edge weights. Would it be possible for doing the same operation for two graphs automatically because I have a large number of graphs. Commented Nov 14, 2019 at 0:04

MapThread[WeightedAdjacencyMatrix[Graph[Range@10, #, EdgeWeight -> #2]] &, {list1, list2}]

TeXForm[Row[MatrixForm /@ %]]

$$\small\left( \begin{array}{cccccccccc} 0 & 0 & 0 & 0.1 & 0 & 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\ \end{array} \right)\left( \begin{array}{cccccccccc} 0 & 0 & 0.7 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0.9 & 0 & 0 & 0 & 0 & 0 & 0 \\ 0 & 0.4 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\ \end{array} \right)$$
SparseArray[#, {10, 10}] & /@ (Rule @@@ Transpose[{list1 /. DirectedEdge -> List, list2}])