gpt4 book ai didi

r - 如何使用 Reduce 将多个矩阵逆序相乘?

转载 作者:行者123 更新时间:2023-12-04 02:10:15 25 4
gpt4 key购买 nike

假设我有一个矩阵列表 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 选项)在做什么?

最佳答案

要反转元素相乘的顺序,只需反转您输入到 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"

关于r - 如何使用 Reduce 将多个矩阵逆序相乘?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28548853/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com