【问题标题】:How can I use crossprod on three or more matrices?如何在三个或更多矩阵上使用 crossprod?
【发布时间】:2019-07-22 02:52:28
【问题描述】:

fast large matrix multiplication in R 这个问题的启发,我想知道是否可以在三个或更多矩阵上使用 crossprod。我正在尝试计算一个包含多个矩阵列表与Map(crossprod,listA,listB) 的叉积的通用列表。我尝试了Map(crossprod,listA,listB,listC),但只得到了listA 和listB 的元素矩阵的叉积。列表 A、B、C 具有相同数量的矩阵。所有矩阵都具有相同的维度。我目前的修复是

result1<-Map(crossprod,listA,listB)
Map(crossprod,result1,listC)  

如何编写一行代码?非常感谢!

【问题讨论】:

  • 试试Reduce("%*%", list(listA, listB, listC)0
  • @akrun:感谢您的回复。我有一个错误。 Error in f(init, x[[i]]) : requires numeric/complex matrix/vector argumentsis.matrix(listA[["matrix1"]] = TRUE 想。

标签: r list matrix-multiplication


【解决方案1】:

一个选项是accumulate

library(purrr)
out2 <- flatten(tail(accumulate(lst1, map2, crossprod), 1))

-检查 OP 的输出

out1 <- Map(crossprod,result1,listC) 
identical(out1, out2)
#[1] TRUE

或者使用base R

do.call(c, tail(Reduce(function(...) Map(crossprod, ...), 
         lst1, accumulate = TRUE), 1))

数据

m1 <- matrix(1:9, 3, 3)
m2 <- matrix(11:19, 3, 3)
listA <- list(m1, m2)
listB <- listA
listC <- listA
lst1 <- mget(paste0("list", c("A", "B", "C")))

【讨论】:

    【解决方案2】:
    library(purrr)
    
    a = matrix(runif(9),ncol=3)
    b = matrix(runif(9),ncol=3)
    c = matrix(runif(9),ncol=3)
    
    ListA = list(a,b)
    ListB = list(a,c)
    ListC = list(b,c)
    
    # list with the lists of matrix
    L = list(ListA,ListB,ListC)
    Reduce("%*%",map(L,~Reduce("%*%",.)))
    
    #Validation
    a %*% b %*% a %*% c %*% b%*% c
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-04
      • 1970-01-01
      • 1970-01-01
      • 2016-08-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-28
      • 2011-08-09
      相关资源
      最近更新 更多