2
$\begingroup$

I want to create a weighted random graph. The random graph is already created

g = BlockRandom[
  RandomGraph[BernoulliGraphDistribution[4, 0.5], DirectedEdges -> True,
    VertexLabels -> "Name"]]

but when I add EdgeWeight -> RandomReal[{-1, 1}, k]] I don't get nothing, for any k I have used

How can I get a RandomGraph with weighted edges?

$\endgroup$
1
  • 1
    $\begingroup$ How does g "know" k? Also, check whether weights can be negative... $\endgroup$ Feb 8, 2018 at 21:27

2 Answers 2

2
$\begingroup$
g = BlockRandom[RandomGraph[BernoulliGraphDistribution[4, 0.5], 
   DirectedEdges -> True, VertexLabels -> "Name", 
   EdgeWeight -> {_ :> RandomReal[{-1, 1}]}, EdgeLabels -> "EdgeWeight"]]

enter image description here

{#, PropertyValue[{g, #}, EdgeWeight]} & /@ EdgeList[g]

{{2 -> 1, -0.424925}, {2 -> 3, 0.767566},{3 -> 2, -0.333168}, {3 -> 4, 0.385857}, {4 -> 1, 0.323498}, {4 -> 3, 0.610081}}

$\endgroup$
1
  • $\begingroup$ Very nice idea with the pattern syntax. There's always something new to discover :) $\endgroup$
    – Szabolcs
    Feb 9, 2018 at 13:08
1
$\begingroup$

What about

BlockRandom[
  g = RandomGraph[BernoulliGraphDistribution[4, 0.5], 
   DirectedEdges -> True, VertexLabels -> "Name"];
  g = Graph[g, EdgeWeight -> RandomReal[{-1, 1}, EdgeCount[g]]];
];
g

?

$\endgroup$
2
  • $\begingroup$ Thank you so much!! $\endgroup$ Feb 8, 2018 at 21:42
  • $\begingroup$ You're welcome! $\endgroup$ Feb 8, 2018 at 22:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.