Autocorrelation computation fails for floats equal to integers
1 view (last 30 days)
Show older comments
Ilya Fomin
on 19 Nov 2019
Commented: Ilya Fomin
on 22 Nov 2019
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");
0 Comments
Accepted Answer
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
More Answers (0)
See Also
Categories
Find more on Creating and Concatenating Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!