简体   繁体   English

将MATLAB代码移植到Python

[英]Porting a MATLAB code to Python

UPDATED TO REFLECT COMMENTS 更新以反映评论

I am required to port a MATLAB code into python. 我需要将MATLAB代码移植到python中。 Unfortunately, despite lot os sleepless nights of debugging and googling, I cannot get my code to run. 不幸的是,尽管在调试和谷歌搜索上经历了很多不眠之夜,但是我却无法运行我的代码。 Here is the MATLAB code in question: 这是有问题的MATLAB代码:

clc;
serie =0:50;
serie = serie - mean(serie);
y = cumsum(serie);
L = length(y);
%Calculate the detrended fluctuation short term coefficient
npuntos = 10;
f1=zeros(1,npuntos);
for n1=4:16
%Segmentation
seg =(1:n1:L);
%disp(length(seg))
yn = zeros(1,L);
    for k = 1:length(seg)-1
        yaux = y(seg(k):seg(k+1)-1);
        x = 1:length(yaux);
        A=[sum(x.^2),sum(x); sum(x),length(x)];
        C=[sum(x.*yaux);sum(yaux)];
        v=inv(A)*C;
        a=v(1); b=v(2);
        pen=a;
        ord=b;
        ytrend = pen*x + ord;
        yn(seg(k):seg(k+1)-1) = ytrend';
    end
f1(n1) = sqrt((1/seg(end)).*sum((y(1:seg(end)-1)-yn(1:seg(end)-1)).^2));
end
n1=4:16;
f1=f1(4:end);
p1 = polyfit(log10(n1(1:end-2)),log10(f1(1:end-2)),1);
alpha1 = p1(1);
disp(alpha1)

My attempt to translate the code into python goes as follows: 我将代码翻译成python的尝试如下:

 import numpy as np data = np.arange(start=0, stop=51, step=1) data = data.transpose() data = data - np.mean(data) y = np.cumsum(data) L = len(y) # Estimate the value of alpha1 npuntos = 12 f1 = [0] * npuntos for i, n1 in enumerate(np.arange(start=4, stop=16, step=1)): seg = np.arange(start=0, stop=L, step=n1) # Potential error yn = [0] * L for k in np.arange(start=0, stop=len(seg)-1, step=1): # Potential Error yaux = y[seg[k]:seg[k + 1]-1] # Potential Error x = np.arange(start=1, stop=len(yaux) + 1, step=1) A = [[sum(x ** 2), sum(x)], [sum(x), len(x)]] C = [[sum(x * yaux)], [sum(yaux)]] v = (np.linalg.inv(A)).dot(C) pen = v[0] ord = v[1] ytrend = pen * x + ord yn[seg[k]: seg[k + 1] - 1] = ytrend f1[i] = np.sqrt((1 / seg[-1]) * sum((y[1:seg[-1] - 1] - yn[1:seg[-1] - 1]) ** 2)) n1 =np.arange(start=4, stop=16, step=1) f1 = f1[4:] xx =np.log10(n1[1: - 2]) yy=np.log10(f1[1: - 2]) print(len(xx)) print(len(yy)) p1 = np.polyfit(xx, yy, 1) alpha1 = p1[1] print(alpha1) 

Unfortunately, I get TypeError when the program is executing this line 不幸的是,程序执行此行时出现TypeError

p1 = np.polyfit(xx, yy, 1)

This is indeed expected as xx is of length 9 while xx is just 5. By using try/catch block as suggested in the comment, 确实可以预期,因为xx的长度为9,而xx的长度仅为5。通过使用注释中建议的try / catch块,

try:
    f1[n1] = np.sqrt((1 / seg[-1]) * sum((y[1:seg[-1] - 1] - yn[1:seg[-1] - 1]) ** 2))
except IndexError:
    f1.append(np.sqrt((1 / seg[-1]) * sum((y[1:seg[-1] - 1] - yn[1:seg[-1] - 1]) ** 2)))

the error is fixed by the output is completely wrong. 错误是由输出修正的,完全是错误的。

I have gone through the debugger but I cannot quite how the error. 我已经通过调试器,但是我不能完全理解该错误。 Can someone please help? 有人可以帮忙吗? PS -The above snippet is supposed to calculate the Detrended Fluctuation Analysis (DFA) if anyone is interested. PS-如果有人感兴趣,以上代码段应用于计算去趋势波动分析(DFA)

Thats because you have npuntos = 10 so that f1 = [0] * npuntos makes your f1 list 's size equal 10 . 那是因为您的npuntos = 10所以f1 = [0] * npuntos使f1 list的大小等于10 And then you iterate over 然后你遍历

for n1 in np.arange(start=4, stop=16, step=1):

And accessing f1[n1] which from 10 to 15 will give you an IndexError 并访问从1到15的f1[n1]会给您一个IndexError

UPDATE UPDATE

First of all you can use np.zeros((5,), dtype=np.int) since you already using np module. 首先,您可以使用np.zeros((5,), dtype=np.int)因为您已经在使用np模块。

Secondly to figure out the thing with IndexError . 其次,用IndexError找出问题。 Personally i don't want to fall into mathematical problem that you are solving, so the solution won't be the best. 我个人不想陷入您要解决的数学问题,因此解决方案将不是最佳解决方案。 Just a slight change. 只是稍有变化。 I believe that you know that Python indexing is zero based. 我相信您知道Python索引是从零开始的。 Since that you will start populating your at 5th element. 从那开始,您将在第5个元素中开始填充。 I'm not sure that you want it. 我不确定您是否想要它。 You can do enumerate(np.arange(start=4, stop=16, step=1)) to create zero based indexing to your list: 您可以enumerate(np.arange(start=4, stop=16, step=1))以创建从零开始的索引到列表:

for i, n1 in enumerate(np.arange(start=4, stop=16, step=1)):
    ...
    f1[i] = np.sqrt((1 / seg[-1]) * sum((y[1:seg[-1] - 1] - yn[1:seg[-1] - 1]) ** 2))

But len(np.arange(start=4, stop=16, step=1)) is 12 not the size you creating your f1 ( 10 ). len(np.arange(start=4, stop=16, step=1))12不是你创建的尺寸f110 )。 So from that point you can create 12 element list. 因此,从那时起您可以创建12元素列表。

npuntos = 12
f1 = [0] * npuntos  # or np.zeros((5,), dtype=np.int)

Or you can do append ing values as it done in MATLAB(as @nekomatic noted) if it's required. 或者,你可以做append ,如果它需要ING值,因为它在MATLAB进行(如@nekomatic说明)。

So you need to wrap 所以你需要包装

f1[n1] = np.sqrt((1 / seg[-1]) * sum((y[1:seg[-1] - 1] - yn[1:seg[-1] - 1]) ** 2))

in try / except : try / except

try:
    f1[n1] = np.sqrt((1 / seg[-1]) * sum((y[1:seg[-1] - 1] - yn[1:seg[-1] - 1]) ** 2))
except IndexError:
    f1.append(np.sqrt((1 / seg[-1]) * sum((y[1:seg[-1] - 1] - yn[1:seg[-1] - 1]) ** 2)))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM