Autocorrelation computation fails for floats equal to integers

1 view (last 30 days)
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

Accepted Answer

Alexandre Turenne
Alexandre Turenne on 21 Nov 2019
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 Comment
Ilya Fomin
Ilya Fomin on 22 Nov 2019
Thank you for expalantion! That makes everything very clear. I need to add a manual check for the variance

Sign in to comment.

More Answers (0)

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Products


Release

R2019b

Community Treasure Hunt

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

Start Hunting!