# Add weighted edge to a graph in Mathematica 8

Is it possible to add an edge with a specific weight to a Mathematica Graph object? The function EdgeAdd has no option for the weights, nor the AddEdge function from the GraphUtilities package.

I want to modify the edge 1-4 of the CompleteGraph for example, how should I do that?

For V9 and up. (you haven't specified your version in your question)

g = CompleteGraph;
PropertyValue[{g, UndirectedEdge[1, 2]}, EdgeWeight] = 2;


$\left( \begin{array}{cccc} 0 & 2 & 1 & 1 \\ 2 & 0 & 1 & 1 \\ 1 & 1 & 0 & 1 \\ 1 & 1 & 1 & 0 \\ \end{array} \right)$

• Ooooooooookay. I'm out!
– Öskå
Sep 30, 2014 at 12:22
• @Öskå The introduction of PropertyWhatever[] in v9 added a nice layer to access graph properties. It's still immature in my opinion. Sep 30, 2014 at 12:24
• Well, still better than what I did..
– Öskå
Sep 30, 2014 at 12:25
• No sorry, this does not work in Mathematica 8! Sep 30, 2014 at 12:37
• @linello If you Mma version isn't the current one you should state that in your question! ;D Sep 30, 2014 at 12:50

I'm not sure I quite understand what you intend to do with EdgeAdd thus I will only answer the "I want to modify the edge 1-4 of the CompleteGraph" question.

Here I modify the edge 1 <-> 4 and 1 <-> 2 for generalisation purposes:

g = CompleteGraph;
weightsVal = {a, b}; (* in the same order as {1 <-> 4, 1 <-> 2}*)
weights = ReplacePart[Array[1 &, Length@EdgeList@g],
Rule @@@ Thread@{Flatten[Position[EdgeList@g, #] & /@ {1 <-> 4, 1 <-> 2}], weightsVal}]
Graph[EdgeList@g, AbsoluteOptions[g, VertexCoordinates],
EdgeWeight -> weights,
EdgeLabels -> Rule @@@ Thread@{EdgeList@g, weights},
VertexLabels -> "Name", ImagePadding -> 10] $\left( \begin{array}{ccccc} 0 & b & 1 & a & 1 \\ b & 0 & 1 & 1 & 1 \\ 1 & 1 & 0 & 1 & 1 \\ a & 1 & 1 & 0 & 1 \\ 1 & 1 & 1 & 1 & 0 \\ \end{array} \right)$