statsstud
statsstud

Reputation: 3

For loop in R not working as expected

I need to write the following in an R program:

X[,1] = (C[1,1]*Y[,1])+(C[1,2]*Y[,2])+(C[1,3]*Y[,3]) + mu[1] 
X[,2] = (C[2,1]*Y[,1])+(C[2,2]*Y[,2])+(C[2,3]*Y[,3]) + mu[2]
X[,3] = (C[3,1]*Y[,1])+(C[3,2]*Y[,2])+(C[3,3]*Y[,3]) + mu[3]

I'm writing the following:

for (i in 1:3){
   for (j in 1:3) {
       X[,i] = sum((C[i,j]*Y[,j]))+ mu[i] 
   }
}

but the answer is not the same as writing all the above. Can anyone help?

Upvotes: 0

Views: 106

Answers (1)

Adela
Adela

Reputation: 1797

There is no need for for-loop in your calculation. Let's say that your data are something like this:

set.seed(1)
C = matrix(1:9, nrow = 3, ncol = 3)
C
     [,1] [,2] [,3]
[1,]    1    4    7
[2,]    2    5    8
[3,]    3    6    9

Y = 1:3
mu = rnorm(3)
mu
[1] -0.6264538  0.1836433 -0.8356286

Then simply you can write:

X = C%*%Y + mu
X
         [,1]
[1,] 29.37355
[2,] 36.18364
[3,] 41.16437

With your for-loop you actually calculate X[i] as C[i,3]*Y[,3]+ mu[i] because you rewrite the value of X[i] in each j-loop.

If you insist on using for-loop solution, use only one for loop:

for (i in 1:3){
  X[i] <- sum(C[i, 1:3]*Y) + mu[i]
}
X
         [,1]
[1,] 29.37355
[2,] 36.18364
[3,] 41.16437

Moreover, if the Y is also the matrix, you can try this:

set.seed(1)
C = matrix(1:9, nrow = 3, ncol = 3)
Y = matrix(1:9, nrow = 3, ncol = 3)
mu = rnorm(3)

X = C%*%Y + mu

X <- matrix(0, nrow = 3, ncol = 3)
for (i in 1:3){
  for (j in 1:3){
    X[i, j] <- sum(C[i, ]*Y[, j]) + mu[i]
  }
}

Upvotes: 4

Related Questions