Matlab函数转换为Python函数

Conversion of Matlab function into Python function

下面的函数是在Matlab上写的。现在,我需要编写一个等效的 python 函数来生成与 Matlab 类似的输出。能帮忙写下代码吗?

function CORR=function_AutoCorr(tau,y)

% This function will generate a matrix, Where on-diagonal elements are autocorrelation and 
% off-diagonal elements are cross-correlations
% y is the data set. e.g., a 10 by 9 Matrix.
% tau is the lag value. e.g. tau=1

Size=size(y);
N=Size(1,2); % Number of columns
T=Size(1,1); % length of the rows
for i=1:N
  for j=1:N
      temp1=0;
    for t=1:T-tau
    G=0.5*((y(t+tau,i)*y(t,j))+(y(t+tau,j)*y(t,i)));
    temp1=temp1+G;
    end
    CORR(i,j)=temp1/(T-tau);
  end
end
end

假设 y 是一个 numpy 数组,它会非常接近类似(虽然我没有测试过):

import numpy as np

def function_AutoCorr(tau, y):
    Size = y.shape
    N = Size[1]
    T = Size[0]
    CORR = np.zeros(shape=(N,N))
    for i in range(N):
        for j in range(N):
            temp1 = 0
            for t in range(T - tau):
                G=0.5*((y[t+tau,i]*y[t,j])+(y[t+tau,j]*y[t,i]))
                temp1 = temp1 + G
            CORR[i, j] = temp1/(T - tau)
    return CORR

y = np.array([[1,2,3], [4,5,6], [6,7,8], [13,14,15]])
print(y)
result = function_AutoCorr(1, y)
print(result)

此示例的结果 CORR 矩阵是:

如果你想 运行 不同 tau 值的函数,你可以在 Python:

result = [function_AutoCorr(tau, y) for tau in range(1, 11)]

结果将是一个自相关矩阵列表,它们是 numpy 数组。这种语法称为列表理解。

您可能想要使用 NumPy。他们甚至还有 guide for Matlab users.

这里有一些有用的提示。

定义函数

def auto_corr(tau, y):
    """Generate matrix of correlations"""
    # Do calculations
    return corr

获取 numpy 数组的大小

n_rows, n_cols = y.shape

索引

索引从 0 开始,使用方括号 ([]) 而不是圆括号。