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
    $\begingroup$ How does g "know" k? Also, check whether weights can be negative... $\endgroup$ – David G. Stork Feb 8 '18 at 21:27
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$
  • $\begingroup$ Very nice idea with the pattern syntax. There's always something new to discover :) $\endgroup$ – Szabolcs Feb 9 '18 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$
  • $\begingroup$ Thank you so much!! $\endgroup$ – Liuba Orlova Feb 8 '18 at 21:42
  • $\begingroup$ You're welcome! $\endgroup$ – Henrik Schumacher Feb 8 '18 at 22:01

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.