3
$\begingroup$

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};

WeightedAdjacencyGraph[SparseArray[arrayR /. {0 -> Infinity}]]

Any suggestion on how to do it with big graphs?

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

IGraph/M has a function for this.

enter image description here

Performance test:

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

wam = WeightedAdjacencyMatrix[g];

IGWeightedAdjacencyGraph[wam]; // RepeatedTiming
(* {0.014, Null} *)
$\endgroup$
1
$\begingroup$

A random graph with 1000 nodes and 5000 edges

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

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

enter image description here

versus

WeightedAdjacencyGraph[SparseArray[arrayR /. 0 -> ∞, {1000, 1000}]] // AbsoluteTiming

enter image description here

(Still on version 9, so cannot use IGraph/M)

$\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.