How could I translate this Python code to Matlab?
2 次查看(过去 30 天)
显示 更早的评论
I have this python code that I would like to convert to Matlab code. Could anyone help me convert from one language to the other?
The code is as follows:
class Peak:
def __init__(self, startidx):
self.born = self.left = self.right = startidx
self.died = None
def get_persistence(self, seq):
return float("inf") if self.died is None else seq[self.born] - seq[self.died]
def get_persistent_homology(seq):
peaks = []
# Maps indices to peaks
idxtopeak = [None for s in seq]
# Sequence indices sorted by values
indices = range(len(seq))
indices = sorted(indices, key = lambda i: seq[i], reverse=True)
# Process each sample in descending order
for idx in indices:
lftdone = (idx > 0 and idxtopeak[idx-1] is not None)
rgtdone = (idx < len(seq)-1 and idxtopeak[idx+1] is not None)
il = idxtopeak[idx-1] if lftdone else None
ir = idxtopeak[idx+1] if rgtdone else None
# New peak born
if not lftdone and not rgtdone:
peaks.append(Peak(idx))
idxtopeak[idx] = len(peaks)-1
# Directly merge to next peak left
if lftdone and not rgtdone:
peaks[il].right += 1
idxtopeak[idx] = il
# Directly merge to next peak right
if not lftdone and rgtdone:
peaks[ir].left -= 1
idxtopeak[idx] = ir
# Merge left and right peaks
if lftdone and rgtdone:
# Left was born earlier: merge right to left
if seq[peaks[il].born] > seq[peaks[ir].born]:
peaks[ir].died = idx
peaks[il].right = peaks[ir].right
idxtopeak[peaks[il].right] = idxtopeak[idx] = il
else:
peaks[il].died = idx
peaks[ir].left = peaks[il].left
idxtopeak[peaks[ir].left] = idxtopeak[idx] = ir
# This is optional convenience
return sorted(peaks, key=lambda p: p.get_persistence(seq), reverse=True)
A big thanks to anyone who can assist me.
0 个评论
采纳的回答
M
2018-8-6
If you want to use your Python code into matlab, you can use: https://mathworks.com/help/matlab/call-python-libraries.html
If you need to convert it, can you detail what part is the problem?
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Call Python from MATLAB 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!