Home > Software engineering >  For loop in R calculation wrong result
For loop in R calculation wrong result

Time:02-19

I want to calculate the sum_{i}^{n} x_{i}^2 * lambda^(n-i) / sum_{i}^{n} lambda^(n-i) enter image description here

Doing so in R i manage to do the following.But zeros occured.What am i doing wrong?


n = 10
x = seq(1,n,1);x
lambda = 0.99 
mat = 0 
for (i in 2:n) {
  mat = (lambda^(n-i)*x[i-1]^2) /  (lambda^(n-i))
}
mat


the result must be the variance of each entry x_{i}

CodePudding user response:

Very well, I will try to see if this is what you need @The Red:

n <-  10
x <-  seq(1,n,1);x
lambda <-  0.99 
mat <- 0
vect_mat <- rep(0, n-1); vect_mat
for (i in 2:n) {
  mat <-  mat   (lambda^(n-i)*x[i-1]^2) /  (lambda^(n-i))
  vect_mat[i-1] <- mat
}
mat
vect_mat

After running it, it results in:

> mat
[1] 285
> vect_mat
[1]   1   5  14  30  55  91 140 204 285

Please accept the answer if this is what you need.

  • Related