finding cycles in directed graph
Show older comments
I am creating a random adjacency matrix for a directed graph and I want to find the cycles. I am using the findcycles function that I found online
I have the following code
rand('seed',1)
n=5;
A=zeros(5);
x=zeros(1,n);
for i=1:n
A(:,i)=randperm(n);
end
A
adj=zeros(n);
for i=1:n
adj(i,A(1,i))=1;
end
view(biograph(adj))
findcycles(adj)
But I get the following error, any ideas?
Warning: Self connecting nodes are not allowed, ignoring the diagonal of CM.
> In biograph (line 160)
In tops (line 13)
Error: File: findcycles.m Line: 5 Column: 10
Invalid expression. Check for missing multiplication operator, missing or unbalanced delimiters, or other syntax error. To construct matrices, use
brackets instead of parentheses.
Error in tops (line 14)
findcycles(adj)
7 Comments
Christine Tobler
on 6 Apr 2020
This sounds like there's a bug in findcycles.m (an invalid expression on line 5). Where did you find it?
Josué Ortega
on 6 Apr 2020
Christine Tobler
on 6 Apr 2020
I can't really help without knowing the definition of the findcycles function.
Josué Ortega
on 6 Apr 2020
Christine Tobler
on 7 Apr 2020
Here's a way that you can change the function to return all the cycles into a cell array:
function pathCell = findcyclesMod(G)
numNodes = size(G,1);
pathCell = {};
for n = 1:numNodes
[D,P]=graphtraverse(G,n);
for d = D
if G(d,n)
pathCell{end+1} = graphpred2path(P,d);
end
end
G(n,:)=0;
end
A cell array is a datastructure where every element can contain an array of varying size, so each element of pathCell contains a vector that represents one path.
Looking at the findcycles function, it seems this won't find all the cycles. In an example:

Here findcycles returns the following cycles:
1 5
1 5 2 3
2 3 5
2 3 5 6 4
3 5 6
3 5 6 4
4 6
This is not showing the possible cycle [2 6 4], for example.
Would you mind telling a bit more about what your requirements are for findcycles? Do you need all cycles in a graph, or just a cycle for any node that contains a cycle? Many of the possible cycles can be just recombinations of other existing cycles (for example in a complete graph (a graph where every pair of two nodes is connected by an edge), any list of nodes would be a cycle, leading to a very long list even for small graphs.
Emanuele Giacomuzzo
on 7 Mar 2021
I'm trying to make this code work for myself, but I have problems in running the graphtraverse function. The graph I am working with is - according to MATLAB - a non-sparse one. So the function won't work on it. Is there any function like graphtraverse that works on non-sparse matrices?
The attached file is my non-sparse adjacency matrix.
Cheers!
Emanuele Giacomuzzo
on 9 Mar 2021
Got it! I solved the problem by converting my adjacency matrix using the sparse function.
Answers (0)
Categories
Find more on Mathematics in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!