18 views (last 30 days)

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):

self.graph[u].append(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"

else:

print "Graph has no cycle"

# Thanks to Divyanshu Mehta for contributing this code

Guillaume
on 1 Apr 2019

Edited: 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

Opportunities for recent engineering grads.

Apply Today
## 1 Comment

## Direct link to this comment

https://au.mathworks.com/matlabcentral/answers/453655-how-could-i-change-this-python-code-to-matlab#comment_688513

⋮## Direct link to this comment

https://au.mathworks.com/matlabcentral/answers/453655-how-could-i-change-this-python-code-to-matlab#comment_688513

Sign in to comment.