有没有办法将这种代码转换为n维循环?
Is there the way how to transform this kind of code into cycle for n-dimension?
我有 n = 4 的代码
b_11 <- (1 / 2) * (wi[1] - wi[1] + 1); b_11
b_12 <- (1 / 2) * (wi[1] - wi[2] + 1); b_12
b_13 <- (1 / 2) * (wi[1] - wi[3] + 1); b_13
b_14 <- (1 / 2) * (wi[1] - wi[4] + 1); b_14
b_21 <- (1 / 2) * (wi[2] - wi[1] + 1); b_21
b_22 <- (1 / 2) * (wi[2] - wi[2] + 1); b_22
b_23 <- (1 / 2) * (wi[2] - wi[3] + 1); b_23
b_24 <- (1 / 2) * (wi[2] - wi[4] + 1); b_24
b_31 <- (1 / 2) * (wi[3] - wi[1] + 1); b_31
b_32 <- (1 / 2) * (wi[3] - wi[2] + 1); b_32
b_33 <- (1 / 2) * (wi[3] - wi[3] + 1); b_33
b_34 <- (1 / 2) * (wi[3] - wi[4] + 1); b_34
b_41 <- (1 / 2) * (wi[4] - wi[1] + 1); b_41
b_42 <- (1 / 2) * (wi[4] - wi[2] + 1); b_42
b_43 <- (1 / 2) * (wi[4] - wi[3] + 1); b_43
b_44 <- (1 / 2) * (wi[4] - wi[4] + 1); b_44
trB <- c(b_11, b_12, b_13, b_14,
b_21, b_22, b_23, b_24,
b_31, b_32, b_33, b_34,
b_41, b_42, b_43, b_44)
对于 n 可能大于 4 的其他情况,是否有任何方法可以简化(或循环)它?
(wi[i] 是一个向量)。
公式以防有帮助:
这可以向量化为:
set.seed(0)
wi <- runif(4) #or whatever
0.5* (outer(wi,wi,"-")+1)
生成矩阵。现在代码与 wi
的长度无关。如果您更喜欢当前拥有的向量,则输出可以重塑为:
c(t(0.5* (outer(wi,wi,"-")+1)))
我有 n = 4 的代码
b_11 <- (1 / 2) * (wi[1] - wi[1] + 1); b_11
b_12 <- (1 / 2) * (wi[1] - wi[2] + 1); b_12
b_13 <- (1 / 2) * (wi[1] - wi[3] + 1); b_13
b_14 <- (1 / 2) * (wi[1] - wi[4] + 1); b_14
b_21 <- (1 / 2) * (wi[2] - wi[1] + 1); b_21
b_22 <- (1 / 2) * (wi[2] - wi[2] + 1); b_22
b_23 <- (1 / 2) * (wi[2] - wi[3] + 1); b_23
b_24 <- (1 / 2) * (wi[2] - wi[4] + 1); b_24
b_31 <- (1 / 2) * (wi[3] - wi[1] + 1); b_31
b_32 <- (1 / 2) * (wi[3] - wi[2] + 1); b_32
b_33 <- (1 / 2) * (wi[3] - wi[3] + 1); b_33
b_34 <- (1 / 2) * (wi[3] - wi[4] + 1); b_34
b_41 <- (1 / 2) * (wi[4] - wi[1] + 1); b_41
b_42 <- (1 / 2) * (wi[4] - wi[2] + 1); b_42
b_43 <- (1 / 2) * (wi[4] - wi[3] + 1); b_43
b_44 <- (1 / 2) * (wi[4] - wi[4] + 1); b_44
trB <- c(b_11, b_12, b_13, b_14,
b_21, b_22, b_23, b_24,
b_31, b_32, b_33, b_34,
b_41, b_42, b_43, b_44)
对于 n 可能大于 4 的其他情况,是否有任何方法可以简化(或循环)它? (wi[i] 是一个向量)。
公式以防有帮助:
这可以向量化为:
set.seed(0)
wi <- runif(4) #or whatever
0.5* (outer(wi,wi,"-")+1)
生成矩阵。现在代码与 wi
的长度无关。如果您更喜欢当前拥有的向量,则输出可以重塑为:
c(t(0.5* (outer(wi,wi,"-")+1)))