I have a weighted graph, and I am interested to find k
largest edges with unique nodes.
Currently, I do it in the following manner
maxMatching[mat_,num_]:=Module[{res={},idxMax,aMax,temp=mat},
Table[idxMax=Nearest[temp["NonzeroValues"]->Automatic,Max[temp],1];
aMax=temp["NonzeroPositions"][[idxMax]];
AppendTo[res,aMax];
temp[[First[Flatten[aMax],1]]]=temp[[First[Flatten[aMax],1]]]*0;
temp[[All,Last[Flatten[aMax],1]]]=temp[[ Last[Flatten[aMax],1]]]*0;
temp
,{num}];
res
]
Any suggestion on how to speed up this calculation in huge matrices are welcome.
Edit: I speed up the calculation in factor ~5 by using a mask matrix and multiplication of the original matrix by the mask matrix.
maxMatching2[mat_, num_] :=
Module[{res = {}, idxMax, aMax, temp = mat, maskMatrix, pos1, pos2},
Table[idxMax =
Nearest[temp["NonzeroValues"] -> Automatic, Max[temp], 1];
aMax = temp["NonzeroPositions"][[idxMax]];
AppendTo[res, aMax];
pos1 =
temp[[First[Flatten[aMax], 1]]][
"NonzeroPositions"];(*temp1[[First[Flatten[aMax],1]]]*0;//
AbsoluteTiming*)
pos2 = temp[[All, Last[Flatten[aMax], 1]]]["NonzeroPositions"];
rr = Thread[List[First[Flatten[aMax]], Flatten[pos1]]];
rr2 = Thread[List[Last[Flatten[aMax]], Flatten[pos2]]];
maskMatrix =
SparseArray[Join[rr, rr2] -> 0.0, Dimensions[temp], 1.0];
temp = temp*maskMatrix
, num];
res
]
Edit 2
Assume in the following graph g1
I want to find 2
largest edges with unique nodes.
g1 = Graph[
{1<->2, 2<->3, 3<->4, 4<->5, 4<->6, 5<->6, 6<->7, 6<->8, 7<->8},
EdgeWeight -> {3, 2, 1, 6, 5, 4, 1, 3, 2},
EdgeLabels -> "EdgeWeight"
];
The first edge is the largest edge in the graph and the second edge is edge without common nodes.
The result will be the red edges in the graph