I have this code for 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)
Is there any way how to simplify (or make cycle) it for other cases, where n could be bigger than 4? (wi[i] is a vector).
Formulas in case this helps:
CodePudding user response:
This can be vectorised as:
set.seed(0)
wi <- runif(4) #or whatever
0.5* (outer(wi,wi,"-") 1)
to produce a matrix. Now the code is independent of the length of wi
. If you prefer the vector that you currently have, the output could be reshaped with:
c(t(0.5* (outer(wi,wi,"-") 1)))