Extracting edge weights with Subgraph?
Potential solution could be:
Clear[exWtSuGr];
exWtSuGr[gr_, verts_] := Module[{sg, el, ew, wAg}, {
sg = Subgraph[gr, verts];
el = EdgeList[sg];
ew = PropertyValue[{gr, #}, EdgeWeight] & /@ el;
wAg = Graph[verts, el, EdgeWeight -> ew]
}[[1]]]
GR1 = exWtSuGr[wAg, Range[6]]
WeightedAdjacencyMatrix[GR1] // MatrixForm
Why not just use WeightedAdjacencyGraph
on the relevant part of the weighted adjacency matrix? The only issue with this approach is that WeightedAdjacencyGraph
expects Infinity
for missing edges instead of 0
. The following function accounts for this:
subgraph[g_, v_] := WeightedAdjacencyGraph @ fixBackground @ WeightedAdjacencyMatrix[g][[v, v]]
fixBackground[sa_SparseArray] := Replace[
sa,
Verbatim[SparseArray][a_, b_, _, c__] :> SparseArray[a, b, Infinity, c]
]
Using a version of your example:
SeedRandom[0];
size=10;
rAm=Table[If[Or[i==j,RandomReal[{0,1}]<.8],Infinity,RandomInteger[{1,100}]-1],{i,size},{j,size}];
wAg=WeightedAdjacencyGraph[rAm]
we get (note the correct adjacency matrix):
subgraph[wAg, {1,3,5,7,9}]
WeightedAdjacencyMatrix[%] //MatrixForm //TeXForm
$\left( \begin{array}{ccccc} 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & 14 \\ 95 & 97 & 0 & 0 & 0 \\ 0 & 0 & 25 & 0 & 76 \\ 0 & 0 & 0 & 0 & 0 \\ \end{array} \right)$
The graph looks the same as what is returned by Subgraph
:
Or maybe:
subGraphWeightLookup =
Association[Thread[EdgeList[wAg] ->
DeleteCases[
Flatten[ReplacePart[Normal[WeightedAdjacencyMatrix[wAg]],
Position[rAm, 0] -> -1]], 0]]] /. x_ /; x == -1 -> 0;
(The -1 is a dummy variable allowing reinsertion of '0' elements.)
Subgraph[wAg, Range[6],
EdgeWeight -> (subGraphWeightLookup[#] & /@
EdgeList[Subgraph[wAg, Range[6]]])]
WeightedAdjacencyMatrix[%] // MatrixForm