【问题标题】:Calculate the sum of matrices in a list or a 3D array计算列表或 3D 数组中矩阵的总和
【发布时间】:2011-03-30 09:29:47
【问题描述】:

给定一个 2x2 矩阵的列表(长度 = n),我如何计算所有这些矩阵的总和(并得到一个 2x2 矩阵)?

如果我在 (2 x 2 x n) 维数组中拥有这些矩阵而不是列表,我该怎么做?

【问题讨论】:

标签: arrays list r


【解决方案1】:

列表中的矩阵总和:

Reduce("+", matrix_list)

【讨论】:

  • 非常优雅。我试过do.call 没有成功。我认为我必须尝试理解和使用Reduce函数。
  • 有人知道为什么像MapReduce这样的函数式编程函数都大写吗?
【解决方案2】:

我会弄乱数组,所以如果你有 list 例如:

n <- 5
someList <- lapply(1:n, function(i) matrix(1:4+(i-1)*4,2,2))

将其转换为 3d array

someArray <- array(unlist(someList ), c(2,2,n))

现在你可以使用rowSums

rowSums(someArray, dims=2)
#      [,1] [,2]
# [1,]   45   55
# [2,]   50   60

【讨论】:

  • 我差点找到这个。我缺少的是 dims 参数。
猜你喜欢
  • 1970-01-01
  • 2015-07-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-01
  • 1970-01-01
相关资源
最近更新 更多