I cannot calculate the autocorrelation coefficient

5 vues (au cours des 30 derniers jours)
Nabil Benhadda
Nabil Benhadda le 7 Sep 2020
Réponse apportée : Omega le 12 Juil 2024
Hello everyone,
I am trying to calculate the first order autocorrelation coefficient of a variable as follows:
function f = foauto(x)
x = x(1:end-1);
y = x(2:end);
f = corrcoef(y,x);
end
Work = readtable('ARcal.xlsx');
Work.Groups = findgroups(Work.Numero);
ACOR = splitapply(@foauto,Work.MarketReturn,Work.Groups);
However, I get the following error message when doing so:
Error using splitapply (line 132)
Applying the function 'foauto' to the 1st group of data generated the following error:
X and Y must have the same number of elements.
Error in ARcal (line 64)
ACOR = splitapply(@foauto,Work.MarketReturn,Work.Groups);
I would like to know if anyone could help me with that as normally x and y should have the same number of elements as they treat the same variable Work.MarketReturn for each group.

Réponses (1)

Omega
Omega le 12 Juil 2024
Hi Nabil,
I understand that you are facing issues while calculating the autocorrelation cofficient.
The issue arises because your function 'foauto' modifies the length of 'x' and 'y' by removing the first and last elements, respectively. This results in 'x' and 'y' having different lengths, which causes the 'corrcoef' function to throw an error.
To fix this, you need to adjust your function to ensure 'x' and 'y' have the same length. Here is a revised version of your function:
function f = foauto(x)
y = x(2:end);
x = x(1:end-1);
f = corrcoef(x, y);
end
In this version, 'x' and 'y' are guaranteed to have the same length because they are both derived from the same input vector x but shifted by one element and 'y' is updated first then 'x'.
This should resolve the error and correctly calculate the first-order autocorrelation coefficient for each group.

Catégories

En savoir plus sur Data Preprocessing dans Help Center et File Exchange

Produits


Version

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by