# weighted graph from the sparse matrix

I interested to create a weighted graph from the sparse matrix of weights.

The following code works for small examples, but to the graph, with few thousands of node, it does not work.

arrayR = {{1, 2} -> 1.6608834828359216, {1, 3} ->
1.3176250784021715, {2, 1} -> 1.6608834828359216, {2, 3} ->
3.8979590937707167, {2, 4} -> 2.058499550409593, {3, 1} ->
1.3176250784021715, {3, 2} -> 3.8979590937707167, {3, 4} ->
1.0569052092863416, {4, 2} -> 2.058499550409593, {4, 3} ->
1.0569052092863416, {_, _} -> 0};



Any suggestion on how to do it with big graphs?

• try WeightedAdjacencyGraph[SparseArray[Most @ arrayR, {numberofnodes, numberofnodes}, ∞]]? – kglr Jul 15 '18 at 7:01
• thank you, this approach more efficient and save around 15% of running time – Kiril Danilchenko Jul 15 '18 at 7:15

IGraph/M has a function for this. Performance test:

g = RandomGraph[{5000, 20000}, EdgeWeight -> RandomReal[1, 20000]];

(* {0.014, Null} *)


A random graph with 1000 nodes and 5000 edges

SeedRandom
arrayR = Append[Thread[RandomSample[Tuples[Range, {2}], 5000] ->
RandomReal[1, 5000]], {_, _} -> 0];

WeightedAdjacencyGraph[SparseArray[Most@arrayR, {1000, 1000}, ∞]] // AbsoluteTiming versus

WeightedAdjacencyGraph[SparseArray[arrayR /. 0 -> ∞, {1000, 1000}]] // AbsoluteTiming (Still on version 9, so cannot use IGraph/M)