MATLAB Answers


How could I change this Python code to Matlab?

Asked by Naime
on 1 Apr 2019
Latest activity Commented on by Guillaume
on 1 Apr 2019
This is python code. I want to write this code in matlab. is there any tools for that?
# Python program to detect cycle
# in a graph
from collections import defaultdict
class Graph():
def __init__(self,vertices):
self.graph = defaultdict(list)
self.V = vertices
def addEdge(self,u,v):
def isCyclicUtil(self, v, visited, recStack):
# Mark current node as visited and
# adds to recursion stack
visited[v] = True
recStack[v] = True
# Recur for all neighbours
# if any neighbour is visited and in
# recStack then graph is cyclic
for neighbour in self.graph[v]:
if visited[neighbour] == False:
if self.isCyclicUtil(neighbour, visited, recStack) == True:
return True
elif recStack[neighbour] == True:
return True
# The node needs to be poped from
# recursion stack before function ends
recStack[v] = False
return False
# Returns true if graph is cyclic else false
def isCyclic(self):
visited = [False] * self.V
recStack = [False] * self.V
for node in range(self.V):
if visited[node] == False:
if self.isCyclicUtil(node,visited,recStack) == True:
return True
return False
g = Graph(4)
g.addEdge(0, 1)
g.addEdge(0, 2)
g.addEdge(1, 2)
g.addEdge(2, 0)
g.addEdge(2, 3)
g.addEdge(3, 3)
if g.isCyclic() == 1:
print "Graph has a cycle"
print "Graph has no cycle"
# Thanks to Divyanshu Mehta for contributing this code

  1 Comment

I don't know of any automatic tools to convert Python to Matlab, but you can call Python from Matlab and the reverse.

Sign in to comment.

1 Answer

Answer by Guillaume
on 1 Apr 2019
Edited by Guillaume
on 1 Apr 2019

As Rik says there's no tool to convert python code into matlab so you'd have to do that manually, first by understanding what the python code is doing, then by writing the equivalent in matlab.
Of course, if you don't know what the python code is doing you have a problem. (But why are you using code your don't understand?)
Saying that, the code you show is trivially converted into matlab since matlab has built-in classes for graphs. The particular code shown is for a directed graph, digraph in matlab, so:
g = digraph;
g = addedge(g, 0, 1);
g = addedge(g, 0, 2);
g = addedge(g, 1, 2);
g = addedge(g, 2, 0);
g = addedge(g, 2, 3);
g = addedge(g, 3, 3);
g.isdag %is graph directly acyclic or not?
edit: stupid autocorrect inserted the wrong words


As I said if you want to know if a directed graph has cycles, use isdag. It will return true if there's no cycle and false otherwise. No need to write your own code.
Sorry, I mean I want to find all cycle in graph using DFS. Not only reture, true or fulse
in my case I want to print out , [1,2,5],[1,2,4,5],[2,3,4],....
This has actually been answered recently, See this post for a simple solution.

Sign in to comment.