R用循环编程

for*_*ter 1 loops r

我有以下3x3方阵a和矢量x:

a = matrix(c(1.0, 0.1, 0.5, 
             0.1, 1.0, 0.9,
             0.5, 0.9, 1.0), nrow=3, ncol=3)

x = c(0.1,0.2,0.3)
Run Code Online (Sandbox Code Playgroud)

我想基本上使用矩阵和向量的上三角形来遵循公式

y = (a12 - (x1/x2)^2 + (a13 - x1/x3)^2 + (a23 - x2/x3)^2
Run Code Online (Sandbox Code Playgroud)

我在上面的公式中使用了以下用于R的循环,我收到以下错误:

Error in a[i, j] : subscript out of bounds
Run Code Online (Sandbox Code Playgroud)

如果你能做错什么事我能不能告诉我,我将不胜感激.

## initialize y
y = 0 

for (i in 1 : nrow(a)-1){
  for (j in i+1 : nrow(a)){
    y = y + ((a[i,j]) - (x[i]/x[j])^2
  }
}
Run Code Online (Sandbox Code Playgroud)

Fer*_*aft 11

你可以使用这个来避免循环:

b <- a - outer(x,x,`/`)
sum(b[upper.tri(b)]^2)
Run Code Online (Sandbox Code Playgroud)

结果

[1] 0.2422222
Run Code Online (Sandbox Code Playgroud)