Search code examples
algorithmmatlabgraph

Simplify the graph keeping connectivity


I have some fully connected graph in Matlab. I want to remove small edges iteratively. If removing of some edge will destroy the graph connectivity, then I would like to keep this edge and try to remove next one. I have a Matlab code, which perfectly do it:

close all
clear all
clc
rng(2023)
%% generate fake data
X = rand(100,10);
R = corr(X);
R = (R+R')./2; % remove numerical problems. Make matrix symmetric
G = graph(R.^2,'omitselfloops');
%% simplify the graph
G.Edges.isChecked(:)=0;
G.Edges.edgeID=[1:size(G.Edges,1)]';
while true
    
    % find minimal edge, which is not checked already
    notCheckedEdges = G.Edges(G.Edges.isChecked==0,:);
    [~,minID] = min(notCheckedEdges.Weight);
    minID = notCheckedEdges.edgeID(minID); % substitute to original ID
    % remove minimal edges
    G1 = rmedge(G,find(G.Edges.edgeID==minID));
    % check if graph is still connected
    isConnected = numel(unique(conncomp(G1)))==1;
    if isConnected
        G = G1; % remove edge
    else
        G.Edges.isChecked(G.Edges.edgeID==minID)=1; % mark edges as checked and keep it for next iterations
    end
    if all(G.Edges.isChecked==1), break; end % terminate loop when all edges were checked
end

The problem is that this code is very slow and primitive.

Do you know how to improve my code or maybe some ready to use algorithm?


Solution

  • Thanks too Matt Timmermans comment. All I need is:

    G = graph(1-R.^2,'omitselfloops');
    G = minspantree(G);