Add weighted edge to a graph in Mathematica 8

1

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[5] for example, how should I do that?

linello

Posted 2014-09-30T10:13:29.887

Reputation: 245

Answers

2

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

g = CompleteGraph[4]; 
PropertyValue[{g, UndirectedEdge[1, 2]}, EdgeWeight] = 2;
MatrixForm@Normal@WeightedAdjacencyMatrix[g]

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

Dr. belisarius

Posted 2014-09-30T10:13:29.887

Reputation: 112 848

Ooooooooookay. I'm out! – Öskå – 2014-09-30T12:22:48.463

@Öskå The introduction of PropertyWhatever[] in v9 added a nice layer to access graph properties. It's still immature in my opinion. – Dr. belisarius – 2014-09-30T12:24:44.103

Well, still better than what I did.. – Öskå – 2014-09-30T12:25:35.453

No sorry, this does not work in Mathematica 8! – linello – 2014-09-30T12:37:28.050

@linello If you Mma version isn't the current one you should state that in your question! ;D – Dr. belisarius – 2014-09-30T12:50:56.190

Some ideas for Mathematica 8? Meanwhile I switched to directly changing the entries of the weighted adjacency matrix but this is definitely not the best solution in my opinion. – linello – 2014-09-30T13:08:12.937

@linello Graph[] was in its childhood in V8. If you're planning to use it extensively I strongly suggest to upgrade at least to v9. Messing with the WAM isn't that bad .. – Dr. belisarius – 2014-09-30T13:11:22.633

@linello My answer bellow works in v8, I deleted after I saw how easy it could be in v9. – Öskå – 2014-09-30T13:24:53.623

1

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[5]" question.

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

g = CompleteGraph[5];
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]
% // WeightedAdjacencyMatrix // MatrixForm

Mathematica graphics

$\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)$

Öskå

Posted 2014-09-30T10:13:29.887

Reputation: 8 267