Autocorrelation computation fails for floats equal to integers

조회 수: 1 (최근 30일)
Ilya Fomin
Ilya Fomin 2019년 11월 19일
댓글: Ilya Fomin 2019년 11월 22일
Hi all,
I found a peculiar behavior of autocorr function. If I have a row of arbitrary float numbers (which are not integer), it works totally fine. However, if I assign it to an integer value (like 4.0), it fails. Apparently, it looks like matlab stores the value internally as an integer, which causes some out-of-the-range value for float.
Is there any way to avoid such behavior?
Thanks!
figure(1)
subplot(1,2,1)
z(1:500) = 1.9;
autocorr(z)
title({"ACF for 1.9, 500 values:","z(1:500) = 1.9;","autocorr(z)"});
ylabel("ACF");
subplot(1,2,2)
z(1:500) = 4.0; % explicit convertation with cast(4.0,'double') does not help
autocorr(z) % explicit convertation with autocorr(cast(z,'double')) does not help
title({"ACF for 4.0, 500 values:","z(1:500) = 4.0;","autocorr(z)"});
ylabel("ACF");
acf_fail.png

채택된 답변

Alexandre Turenne
Alexandre Turenne 2019년 11월 21일
This is how the autocorr is computed is real life.
1.You find the mean of your series --> mean(z)
2. You find the variance --> var(z)
3.You find the covariance for each lag --> covar(i) = sum((z(i+1:end)-avg.*(z(1:end-i)-avg)/(50-i) where i is the number of lag
4. You calculate the corr with --> covar(i)/var(z)
the covar should always be zero but matlab since to have problems with float numbers which make the function instable returning a variance of 1.8112e-30 and a cov of 1.7749e-30 thats why it gives something close to 1. But in reality it should be NaN like with the integers since the 4th equation for the corr is 0/0.
Code:
avg = mean(z) %0
variance = var(z) %0
for i =1: 20
covar(i) = 1/(50-i)*sum((z(i+1:end)-avg).*(z(1:end-i)-avg)) %0
correl(i) = covar(i)/variance
end
  댓글 수: 1
Ilya Fomin
Ilya Fomin 2019년 11월 22일
Thank you for expalantion! That makes everything very clear. I need to add a manual check for the variance

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

제품


릴리스

R2019b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by