gpt4 book ai didi

r - R 中高效的行式矩阵运算

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

我有2个矩阵M1,M2。对于 M1 中的每一行,我想找到 M1 中该行与 M2 中每一行的乘积的最大值。

我尝试了以下实现,它产生了我想要的结果。

set.seed(1)
st_time = Sys.time()
M1 = matrix(runif(1000*10), nrow=1000, ncol=10)
M2 = matrix(runif(10000*10), nrow=10000, ncol=10)

score = apply(M1, 1, function(x){
w = M2 %*% diag(x)
row_max = apply(w, 1, max)
return(row_max)
})
required_output = t(score)
Sys.time() - st_time

这在我的机器上需要 16 秒。有更快的实现吗?谢谢!

最佳答案

使用 for 循环给我带来了相当大的速度

set.seed(1)
M1 = matrix(runif(1000*10), nrow=1000, ncol=10)
M2 = matrix(runif(10000*10), nrow=10000, ncol=10)

st_time = Sys.time()

tm = t(M2)
out = matrix(0, nr=nrow(M1), nc=nrow(M2))

for(i in 1:nrow(M1)){
out[i, ] = matrixStats::colMaxs(M1[i, ]* tm)
}

Sys.time() - st_time
#Time difference of 1.835793 secs # was ~28secs with yours on my laptop


all.equal(required_output, out)

关于r - R 中高效的行式矩阵运算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44231248/

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