【问题标题】:R, pair-wise product of unknown number of vectors/matricesR,未知数量的向量/矩阵的成对乘积
【发布时间】:2021-07-09 09:46:29
【问题描述】:

我想在基数 R 中制作可变数量的矩阵/向量的成对乘积。 我只有这个丑陋的解决方案(丑陋的是<<-),但直觉上认为存在更好的——也许是递归的——方式,或者甚至是一个函数。我需要prod 的成对版本。

f1 <- function(...) {
  input <- list(...)
  output <- input[[1]]
  sapply(2:length(input), function(m) output <<- output*input[[m]])
  return(output)
}

m1 <- matrix(1:6, ncol = 2)
m2 <- matrix(6:1, ncol = 2)
m3 <- 1/matrix(6:1, ncol = 2)

all(f1(m1,m2,m3) == m1*m2*m3) #[1] TRUE

【问题讨论】:

  • 我说你不​​想要矩阵乘积而是逐元素乘积对吗?
  • 是的 - 没错。

标签: r recursion vector product pairwise


【解决方案1】:

使用Reduce

f1 <- function(...) {
  Reduce(`*`, list(...))
}

all(f1(m1,m2,m3) == m1*m2*m3)
#[1] TRUE

【讨论】:

    猜你喜欢
    • 2019-04-21
    • 1970-01-01
    • 2020-01-17
    • 2018-12-05
    • 1970-01-01
    • 2014-11-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多