Rana Muhammad kashif - 1 month ago 18

R Question

Where Xij is the corresponding term of ith row at jth column and i = 1,2 ; j = 1,2 .

The code I tried is:

`y <- cbind(1:2, 3:4)`

mean_y <- 2

double_summataion = 0

for (i in 1: y[1]) {

for (j in 1:y[2]) {

double_summataion = double_summataion + ((y[i,j] - mean_y)%*%(t(y[i,j])-mean_y))

}

}

Can someone help me rectify this code?

Answer

```
y <- matrix(runif(1000),100,100)
mean <- mean(y)
double_summation = 0
for (i in 1:nrow(y)) {
for (j in 1:ncol(y)) {
double_summation = double_summation + (y[i,j] - mean)*(y[j,i]-mean)
}
}
double_summation
#[1] 10.15864
```

But it's faster to do

```
centered <- y-mean
sum(diag(centered%*%centered))
#[1] 10.15864
```

This works for any value of `mean`

, even if it isn't actually the mean of matrix elements as in your example.

Neither one of these methods will work if your matrix isn't square. If your matrix isn't square I'm not sure what to make of the formula, because you won't be able to sum over all indices.