如何使用Reduce以相反的顺序乘以几个矩阵?

时间:2015-02-16 19:24:21

标签: r

假设我有一个矩阵列表W,我想同时执行W[[1]] %*% W[[2]] %*% W[[3]] %*% W[[4]] %*% ...W[[4]] %*% W[[3]] %*% W[[2]] %*% W[[1]] %*% ...。似乎Reduce(`%*%`, W)Reduce(`%*%`, W, right = T)应该这样做,但这似乎不起作用。下面的代码给出了一个例子:

set.seed(90088)
W <- list(
    matrix(sample(1:5, size = 25, replace = T), ncol = 5),
    matrix(sample(1:5, size = 25, replace = T), ncol = 5),
    matrix(sample(1:5, size = 25, replace = T), ncol = 5),
    matrix(sample(1:5, size = 25, replace = T), ncol = 5)
    )
Reduce(`%*%`, W)
Reduce(`%*%`, W, right = T)
W[[1]] %*% W[[2]] %*% W[[3]] %*% W[[4]]
W[[4]] %*% W[[3]] %*% W[[2]] %*% W[[1]]

有谁知道Reduce(尤其是right = T选项)正在做什么?

1 个答案:

答案 0 :(得分:4)

要反转元素相乘的顺序,只需将您输入的列表中元素的顺序颠倒到Reduce()

Reduce(`%*%`, rev(W))
#       [,1]  [,2]  [,3] [,4]  [,5]
# [1,] 11583  8978  9082 5034 10443
# [2,] 12759  9950  9967 5604 11565
# [3,]  7269  5686  5702 3176  6575
# [4,] 15459 12094 12050 6857 14060
# [5,]  9834  7684  7691 4314  8916

要查看right=TRUE做了什么(并且它有点有趣),请检查更简单的Reduce()调用的中间结果:

Reduce(`*`, 5:1, accumulate=TRUE, right=FALSE)
# [1]   5  20  60 120 120
Reduce(`*`, 5:1, accumulate=TRUE, right=TRUE)
# [1] 120  24   6   2   1

## And a non-commutative function shows even more clearly how right=TRUE works:
Reduce(paste0, letters[1:5], right=TRUE, accumulate=TRUE)
# [1] "abcde" "bcde"  "cde"   "de"    "e"