5
$\begingroup$

I am trying to add weights to the edges of the randomly generated graph as follows:

gErdosSmall = RandomGraph[BernoulliGraphDistribution[10, 0.1], 
  DirectedEdges -> True, 
  EdgeWeight -> RandomReal[{1, 5}, 10]]

But then is I try to get the weighted adjacency matrix of this random graph:

WeightedAdjacencyMatrix[gErdosSmall] // MatrixForm

I get an error saying

"A graph object is expected at position 1 in WeightedAdjacencyMatrix".

Clearly, I am missing something really obvious - what is it?

$\endgroup$
4
$\begingroup$

Notice that your gErdosSmall did not evaluate to a Graph.

gErdosSmall = 
 RandomGraph[BernoulliGraphDistribution[10, 0.1], 
  DirectedEdges -> True, EdgeWeight -> RandomReal[{1, 5}, 10]]
(* RandomGraph[BernoulliGraphDistribution[10, 0.1], 
 DirectedEdges -> True, 
 EdgeWeight -> {2.66631, 1.45058, 4.87004, 4.32779, 2.71257, 1.31485, 
   2.44376, 1.9827, 1.01843, 3.19028}] *)

The issue is that you are setting the EdgeWeight property to a list of 10 elements, but you have no way of knowing how many edges your random graph will have.

Try setting the weights after generating the graph,

gErdosSmall = 
 RandomGraph[BernoulliGraphDistribution[10, 0.1], 
  DirectedEdges -> True]
weights = RandomReal[{1, 5}, EdgeCount @ gErdosSmall]
gErdosSmall = SetProperty[gErdosSmall, EdgeWeight -> weights]

enter image description here

Head @ WeightedAdjacencyMatrix@gErdosSmall
(* SparseArray *)
$\endgroup$
3
$\begingroup$

You can get the desired result in a single step and without having to know the number of edges if you specify the EdgeWeight option as EdgeWeight -> {_ :> RandomReal[{1, 5}]} :

SeedRandom[123]
gErdosSmall = RandomGraph[BernoulliGraphDistribution[10, 0.1], 
    DirectedEdges -> True, EdgeWeight -> {_ :> RandomReal[{1, 5}]}, 
    EdgeLabels -> "EdgeWeight"]

enter image description here

WeightedAdjacencyMatrix[gErdosSmall] // MatrixForm // TeXForm

$\small\left( \begin{array}{cccccccccc} 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 1.67966 & 1.39831 \\ 2.88079 & 0 & 2.61296 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0 & 4.88634 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & 2.25972 & 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 & 1.50312 & 0 & 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & 2.08904 & 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & 3.42299 & 0 & 0 & 3.68705 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\ \end{array} \right)$

$\endgroup$
  • $\begingroup$ This is great, works with SetProperty also to use a pattern $\endgroup$ – Jason B. Jun 12 '18 at 15:26

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.