I have a list of edges as follows.
75 77
77 78
78 79
60 63
61 65
65 67
57 62
62 64
67 81
81 85
I want to separate the connected edges as follows.
75 60 61 57
77 63 65 62
78 67 64
79 81
85
I wrote the following code in Matlab.
edges = [75 77; 77 78; 78 79; 60 63; 61 65; 65 67; 57 62; 62 64; 67 81; 81 85];
visited = zeros(size(edges,1),1);
cEdges = [];
cEdgesC = 1;
cEdges(1,cEdgesC) = edges(1,1);
cEdges(2,cEdgesC) = edges(1,2);
visited(1,1) = 1;
orgR = 1;
orgC = 2;
while sum(visited) <= size(visited,1)
cEdgesR = nnz(cEdges(:,cEdgesC));
currentVertex = cEdges(cEdgesR,cEdgesC);
fprintf('\n%d\t%d',cEdgesR,currentVertex);
[foundR,foundC] = find(edges==currentVertex);
foundR(foundR==orgR) = [];
foundC(foundC==orgC) = [];
while isempty(foundR)
fmt=repmat('%d ',1,cEdgesR);
fprintf('\nLoop found: ');
fprintf(fmt,(cEdges(:,cEdgesC))');
cEdgesC = cEdgesC+1;
orgR = find(visited==0, 1, 'first');
orgC = 1;
cEdges(1,cEdgesC) = edges(orgR,orgC);
cEdges(2,cEdgesC) = edges(orgR,orgC+1);
visited(orgR,1) = 1;
cEdgesR = nnz(cEdges(:,cEdgesC));
currentVertex = cEdges(2,cEdgesC);
fprintf('\n%d\t%d',cEdgesR,currentVertex);
[foundR,foundC]=find(edges==currentVertex);
foundR(foundR==orgR) = [];
foundC(foundC==orgC) = [];
if isempty(foundR)
// What to do here?
end
end
fprintf('\t%d\t%d',foundR,foundC);
orgR = foundR;
if foundC == 1
cEdges(cEdgesR+1,1) = edges(foundR,foundC+1);
orgC = foundC+1;
else
cEdges(cEdgesR+1,1) = edges(foundR,foundC-1);
orgC = foundC-1;
end
visited(foundR,1) = 1;
end
The code runs in a loop with no stop. I feel problem is at the end of inner while loop. How may I jump back to the beginning of inner while loop if the same condition is met at the end again? Thank you.
If you not consider cyclic cases and backward connection than this should be easy problem.
edges = [75 77; 77 78; 78 79; 60 63; 61 65; 65 67; 57 62; 62 64; 67 81; 81 85];
NumEdges=size(edges,1);
visited = false(NumEdges,1);
List=cell(0);
k=0;
for i=1:NumEdges
if ~visited(i)
k=k+1;
List{k}=edges(i,1);
Idx=i;
while ~isempty(Idx)
visited(Idx)=true;
List{k}(end+1)=edges(Idx,2);
Idx=find(edges(:,1)==edges(Idx,2) & ~visited,1);
end
end
end
celldisp(List)