1
$\begingroup$

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?

$\endgroup$
0

2 Answers 2

2
$\begingroup$

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

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

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

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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