我想得到减法矩阵,即通过从其他行中减去每一行得到的矩阵。我的MWE低于(未按预期工作)。得到的矩阵应为36 * 3,包含来自其他行的每行的减去值。感谢
X <-
matrix(
data=
c(
5, 9, 20
, 6, 11, 2
, 4, 5, 20
, 6, 9, 46
, 5, 7, 1
, 3, 1, 12
)
, nrow = 6
, ncol = 3
, byrow=TRUE
)
XSub <-
matrix(data=NA, nrow=nrow(X)^2, ncol=ncol(X))
for(i in 1:nrow(X)){
for(j in 1:nrow(X)){
XSub[i+j-1, ] <- X[i, ]-X[j,]
}
}
XSub
答案 0 :(得分:2)
我相信这是你想要的(避免使用循环):
X <-
matrix(
data=
c(
5, 9, 20
, 6, 11, 2
, 4, 5, 20
, 6, 9, 46
, 5, 7, 1
, 3, 1, 12
)
, nrow = 6
, ncol = 3
, byrow=TRUE
)
comb <- expand.grid(x1=1:nrow(X), x2=1:nrow(X))
XSub <- X[comb$x1,] - X[comb$x2,]
rownames(XSub) <- paste(comb$x1, comb$x2, sep="-")
结果如下:
> XSub
[,1] [,2] [,3]
1-1 0 0 0
2-1 1 2 -18
3-1 -1 -4 0
4-1 1 0 26
5-1 0 -2 -19
6-1 -2 -8 -8
1-2 -1 -2 18
2-2 0 0 0
3-2 -2 -6 18
4-2 0 -2 44
5-2 -1 -4 -1
6-2 -3 -10 10
1-3 1 4 0
2-3 2 6 -18
3-3 0 0 0
4-3 2 4 26
5-3 1 2 -19
6-3 -1 -4 -8
1-4 -1 0 -26
2-4 0 2 -44
3-4 -2 -4 -26
4-4 0 0 0
5-4 -1 -2 -45
6-4 -3 -8 -34
1-5 0 2 19
2-5 1 4 1
3-5 -1 -2 19
4-5 1 2 45
5-5 0 0 0
6-5 -2 -6 11
1-6 2 8 8
2-6 3 10 -10
3-6 1 4 8
4-6 3 8 34
5-6 2 6 -11
6-6 0 0 0