# Adding/deleting weighted edges to a weighted graph

How can I add and delete weighted edges in a weighted graph?

Using Graph in Mathematica I want to add a weighted edge to a weighted graph. The problem is EdgeAdd seems to always return an unweighted graph. For example:

g = Graph[{1 \[UndirectedEdge] 2, 2 \[UndirectedEdge] 3}, EdgeWeight -> {5, 11}]
g1 = EdgeDelete[g, 2 \[UndirectedEdge] 3]
g2 = EdgeAdd[g, 1 \[UndirectedEdge] 3]


Here, g1 has its edge weights messed up, so WeightedAdjacencyMatrix does not work. It seems the list of edge weights is too long since no element has been deleted. g2, on the other hand, is an unweighted graph. I even tried wrapping the added edge in

Property[1 \[UndirectedEdge] 3, EdgeWeight -> 13]


but that only got me an error when supplied to EdgeAdd.

I can bypass the EdgeDelete thing quite easily by afterwards readjusting the EdgeWeights list, but I haven't found a way to solve the EdgeAdd problem.

The problem here is that EdgeDelete[G, e] does not remove the appropriate weight $w_e$ from the properties of graph $G$ (I would say this is a bug, though it is the last one in a very long list for Graph...). First, set up explicit edge and weight lists, and a one-to-one mapping for conversions:

e = {1 \[UndirectedEdge] 2, 2 \[UndirectedEdge] 3};
w = {5, 11};

g = Graph[e, EdgeWeight -> w, VertexLabels -> "Name", ImagePadding -> 10]; g1 = EdgeDelete[g, 2 \[UndirectedEdge] 3]; It is clearly reported by PropertyValue that g1 still keeps unnecessary weights.

Now one can rely on SetProperty, though it requires possibly tedious tracking and re-setting of weights:

g2 = SetProperty[EdgeDelete[g, 2 \[UndirectedEdge] 3],
EdgeWeight -> (DeleteCases[e, 2 \[UndirectedEdge] 3] /. r)]; The same method works for EdgeAdd:

g3 = SetProperty[EdgeAdd[g2, 1 \[UndirectedEdge] 3],
EdgeWeight -> Append[PropertyValue[g2, EdgeWeight], 4]]; 