How could I change this Python code to Matlab?
9 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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
1 Kommentar
Rik
am 1 Apr. 2019
I don't know of any automatic tools to convert Python to Matlab, but you can call Python from Matlab and the reverse.
Antworten (1)
Guillaume
am 1 Apr. 2019
Bearbeitet: Guillaume
am 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
7 Kommentare
Siehe auch
Kategorien
Mehr zu Call Python from MATLAB finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!