Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

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.

share|improve this question
add comment

1 Answer 1

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};
r = Thread[e -> w];

g = Graph[e, EdgeWeight -> w, VertexLabels -> "Name", ImagePadding -> 10];
{PropertyValue[g, EdgeWeight], MatrixForm@WeightedAdjacencyMatrix@g, g}

Mathematica graphics

g1 = EdgeDelete[g, 2 \[UndirectedEdge] 3];
{PropertyValue[g1, EdgeWeight], MatrixForm@WeightedAdjacencyMatrix@g1, g1}

Mathematica graphics

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)];
{PropertyValue[g2, EdgeWeight], MatrixForm@WeightedAdjacencyMatrix@g2, g2}

Mathematica graphics

The same method works for EdgeAdd:

g3 = SetProperty[EdgeAdd[g2, 1 \[UndirectedEdge] 3], 
              EdgeWeight -> Append[PropertyValue[g2, EdgeWeight], 4]];
{PropertyValue[g3, EdgeWeight], MatrixForm@WeightedAdjacencyMatrix@g3, g3}

Mathematica graphics

share|improve this answer
add comment

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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