The following function is written on Matlab. Now, I need to write an equivalent python function that will produce a similar output as Matlab. Can you help write the code, please?
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
CodePudding user response:
Assuming that y
is a numpy Array, it would be pretty near something like (although I have not tested):
def function_AutoCorr(tau, y):
Size = y.shape
N = Size[0]
T = Size[1]
CORR = np.zeros(shape=(N,N))
for i in range(N):
for j in range(N):
temp1 = 0
for t in range(1, 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)
CodePudding user response:
You'll probably want to use NumPy. They even have a guide for Matlab users.
Here are some useful tips.
Defining a function
def auto_corr(tau, y):
"""Generate matrix of correlations"""
# Do calculations
return corr
Get the size of a numpy array
n_rows, n_cols = y.shape
Indexing
Indexing is 0-based and uses brackets ([]
) instead of parentheses.