![untitled.png](https://www.mathworks.com/matlabcentral/answers/uploaded_files/221082/untitled.png)
To get autocorrelation function of periodic signal with xcorr function
12 views (last 30 days)
Show older comments
![periodic_signal.JPG](https://www.mathworks.com/matlabcentral/answers/uploaded_files/221075/periodic_signal.jpeg)
I couldn't get autocorrelation function of my periodic signal with xcorr() function as I have expected. My signal is periodic and its autocorrelation function should be periodic with same amplitudes, I got transient signal when I used xcorr() function. Where is the mistake?
![autocorrelation_funct.JPG](https://www.mathworks.com/matlabcentral/answers/uploaded_files/221076/autocorrelation_funct.jpeg)
clc,clear,close all
T=2;A=2; %period and amplitude of signal
t=linspace(-4*T,4*T,1000);
x=mod(t,T)
x=A*(-x+A/2)%Periodic signal which it's autcorr. will be determined
plot(t,x,'linewidth',2);
ylim([-4 4]);
grid on
xlabel('t');ylabel('x(t)');title('Real Function, T=2, A=2');
%return
a=xcorr(x,((length(t))/2));
dt=median(diff(t)); % diff() calculates distance between adjacent elements in vector, median() avaraging
a=a*dt; %xcorr function calculate corelation as a discrete time signal, we converted to continous time signal
t(1001)=t(1000)+dt;
plot(t,a,'r');hold on
0 Comments
Answers (1)
Luis J Gilarranz
on 26 May 2019
No idea about xcor function, but you can write a lower level code that does the job:
Autocorrelation is just the pearson correlation coefficient between a time series and the same time series but with a lag. In this code I do the lag-1 autocorrelation inside a moving window of 100 datapoints.
clc,clear,close all
T=2;A=2; %period and amplitude of signal
t=linspace(-4*T,4*T,1000);
x=mod(t,T)
x=A*(-x+A/2)%Periodic signal which it's autcorr. will be determined
%I transpose x so that it works with the code I had
x=x'
HalfMW=50;%half of the moving window
cont=0;
AutCorVsTime=zeros(cont,1);
for d=HalfMW+1:1000-HalfMW
cont=cont+1;
Chunk = x(d-HalfMW:d+HalfMW,1);
SizeChunk = size(Chunk,1);
AutCorVsTime(d,1)=corr(Chunk(2:SizeChunk,1),Chunk(1:SizeChunk-1,1),'rows','complete'); %Pearson correlation coefficient ignoring NaN
end
plot(AutCorVsTime)
And as you can see the resulting figure is indeed periodic.
![untitled.png](https://www.mathworks.com/matlabcentral/answers/uploaded_files/221082/untitled.png)
If you change the size of the moving window the plot obviously changes.
2 Comments
Asrith Pyla
on 6 Jun 2020
Dear Luis, is it possible to determine the auto-correlation function for an image?
Luis J Gilarranz
on 9 Jun 2020
Edited: Luis J Gilarranz
on 9 Jun 2020
Yes, by taking a radious around a pixel. Search for autocorrelation in 2D
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!