steve_bank
Diabetic retinopathy and poor eyesight. Typos ...
Correlation
rhttps://en.wikipedia.org/wiki/Cross-correlation
How it works. In the case of a sine wave when a frequency component of a signal matches the correlation sine the signs of each point match so the product is always positive. When signal components and correlation points do not match in sign the summation is zero or close to it.
w = 2*ma.pi*fr[f]/n divides the sine curve of the correlation function into n pieces.
for j in range(ncor):s = s + y[j+i]*ma.sin(w*j) does the correlation
rhttps://en.wikipedia.org/wiki/Cross-correlation
How it works. In the case of a sine wave when a frequency component of a signal matches the correlation sine the signs of each point match so the product is always positive. When signal components and correlation points do not match in sign the summation is zero or close to it.
w = 2*ma.pi*fr[f]/n divides the sine curve of the correlation function into n pieces.
for j in range(ncor):s = s + y[j+i]*ma.sin(w*j) does the correlation
Code:
import array as ar
import matplotlib.pyplot as plt
import math as ma
import random as rn
n = 1000
tmax = 1
dt = tmax/(n-1)
t = ar.array("d",n*[0])
for i in range(n):t[i] = (i-1)*dt
corr = ar.array("d",n*[0])
y = ar.array("d",n*[0])
fr = ar.array("i",n*[0])
A1 = 1.
A2 = 2.
A3 = 1.5
f1 = 4.
f2 = 8.
f3 = 10.
#3 signals andsone noise
for i in range(n):
y[i] = A1*ma.sin(2.*ma.pi*f1*t[i])
y[i] = y[i] + A2*ma.sin(2*ma.pi*f2*t[i])
y[i] = y[i] + A3*ma.sin(2*ma.pi*f3*t[i])
y[i] = y[i] + rn.random() *10
nfreqs = 10
for f in range(nfreqs):
fr[f] = f+1
s = 0
w = 2*ma.pi*fr[f]/n #divide the argument into n peces
for j in range(n):s = s + y[j]*ma.sin(w*j)
corr[f] = 2.*abs(s)/n
print("Frequency \tCorrelation")
for i in range(nfreqs):
print("%2d \t\t%.5f" %(fr[i],corr[i]))
[fig, p] = plt.subplots(2,1)
p[0].plot(t,y,color='k')
p[0].grid(which='major', color='k',linestyle='--', linewidth=.4)
p[1].vlines(fr,0,corr,colors = 'k')
p[1].grid(which='major', color='k',linestyle='--', linewidth=.4)
plt.show()
Frequency Correlation
1 0.10326
2 0.08844
3 0.00683
4 0.99624
5 0.11656
6 0.22281
7 0.09948
8 2.09447
9 0.12480
10 1.55338