Auto correlation python code | Cross correlation python code

This page covers Auto correlation python code and Cross correlation python code. This correlation code can be used in simulation of time offset estimation of OFDM/OFDMA waveforms.

Introduction: Cross correlation allows assessment of the degree of similarity between two signals. Auto correlation (i.e. correlation of signal with itself) helps identify signal features from impaired signal. Correlation is used in various applications such as pattern recognition, signal detection, security system etc.

In auto correlation, same signal is correlated to itself or with shifted version of it. In cross correlation, two different time series signals are correlated.

Correlation Python script

Following python script can be used for simulating cross correlation and auto correlation functionalities. Developers have to change input vectors as required for auto correlation and cross correlation as mentioned at the beginning of the script.


#Auto and Cross correlation python code
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

#This is cross correlation part
#in1=[1, 2, 3, 4, 5, 6,7,8,9]
#in2=[11,12,13,14,15,16,17,18,19]

#This is for auto correlation part
in1=[1, 2, 3, 4, 5, 6,7,8,9]
in2=[0,0,0,0,1, 2, 3, 4, 5, 6,7,8,9]

print(in1)
print(in2)

if len(in1) > len(in2):
  pad = len(in1)-len(in2)
  in2=np.append([in2],[np.zeros(pad)])
elif len(in1) < len(in2):
  pad = len(in2)-len(in1)
  in1=np.append([in1],[np.zeros(pad)])

out_len = len(in1)
out = np.zeros(out_len)
corr = np.corrcoef(in1, in2)
print(corr)


tmp= in2
tmp = np.transpose(tmp)
i = 0
while i < out_len:
  out[i] = in1[i] * tmp[i]
  i += 1

indexMaxValue = max(out)
print(indexMaxValue)
peak_index = pd.Series(out).idxmax()+1
print("Number of zeros in delayed vector =", len(in2)- peak_index)
print("Index of Max or peak value from start i.e. position 0 =", pd.Series(out).idxmax())
plt.plot(out)
plt.show()


Input for auto correlation python script

Following are the input vectors, respective output and plot for python auto correlation functionality.

#This is for auto correlation part

in1=[1, 2, 3, 4, 5, 6,7,8,9]

in2=[0,0,0,0,1, 2, 3, 4, 5, 6,7,8,9]

Output for auto correlation python snippet

Number of zeros in delayed vector = 4

Index of Max or peak value from start i.e. position 0 = 8

Python auto correlation plot

Input for cross correlation python code

Following are the input vectors, respective output and plot for python cross correlation functionality.

#This is cross correlation part

in1=[1, 2, 3, 4, 5, 6,7,8,9]

in2=[11,12,13,14,15,16,17,18,19]

Output for cross correlation python code

Number of zeros in delayed vector = 0

Index of Max or peak value from start i.e. position 0 = 8

Python cross correlation plot

Other useful DSP codes in Python

Useful Links to MATLAB codes

RF and Wireless tutorials