如何根据需要将其他矩阵的不同值替换为空矩阵

问题描述 投票:0回答:1

我有这 4 个矩阵(分别) 矩阵1

         [,1]   [,2]   [,3]   [,4]   [,5]   [,6]   [,7]   [,8]   [,9]  [,10]  [,11]  [,12]
  [1,] 10.426 10.456 10.481 10.499 10.511 10.517 10.517 10.512 10.501 10.485 10.464 10.437
  [2,] 10.609 10.636 10.656 10.671 10.679 10.682 10.679 10.671 10.658 10.639 10.615 10.585
  [3,] 10.811 10.834 10.851 10.862 10.867 10.866 10.860 10.848 10.832 10.810 10.784 10.751

矩阵2

         [,1]   [,2]   [,3]   [,4]   [,5]   [,6]   [,7]   [,8]   [,9]  [,10]  [,11]  [,12]
  [1,] 18.014 17.986 17.955 17.922 17.886 17.848 17.807 17.763 17.718 17.671 17.624 17.576
  [2,] 17.629 17.598 17.566 17.531 17.494 17.454 17.412 17.368 17.322 17.274 17.226 17.177
  [3,] 17.264 17.232 17.198 17.162 17.124 17.083 17.040 16.995 16.948 16.900 16.851 16.801

矩阵3

         [,1]   [,2]   [,3]   [,4]   [,5]   [,6]   [,7]   [,8]   [,9]  [,10]  [,11]  [,12]
  [1,] 12.716 12.686 12.653 12.619 12.583 12.545 12.502 12.457 12.406 12.351 12.292 12.229
  [2,] 12.920 12.887 12.853 12.817 12.780 12.739 12.696 12.649 12.598 12.543 12.483 12.420
  [3,] 13.098 13.063 13.027 12.990 12.950 12.909 12.864 12.816 12.764 12.708 12.648 12.584

矩阵4

          [,1]    [,2]    [,3]    [,4]    [,5]    [,6]    [,7]    [,8]    [,9]   [,10]
  [1,]  8.9436  8.8955  8.8455  8.7937  8.7403  8.6854  8.6293  8.5724  8.5148  8.4563
  [2,]  9.0707  9.0227  8.9729  8.9213  8.8683  8.8139  8.7583  8.7020  8.6449  8.5869
  [3,]  9.1959  9.1482  9.0988  9.0478  8.9953  8.9416  8.8867  8.8310  8.7746  8.7173
         [,11]   [,12]   
  [1,]  8.3968  8.3365  
  [2,]  8.5280  8.4681 
  [3,]  8.6589  8.5996

我想创建一个新矩阵,其值恰好存储在如上所示的位置点处,新值 = 这 4 个矩阵中同一位置的四个值的平均值。例如。在 [1,1] 处,值将是 (10.426 + 18.014 + 12.716 + 8.9436)/4 = 12.5249 的平均值,依此类推。我的想法是创建一个与这 4 个矩阵具有相同维度的空矩阵,然后使用 for 循环将平均值填充到其中,但我不知道如何创建代码。那里有伸出援助之手吗?非常感谢(在 R 中)。

r matrix replace mean
1个回答
0
投票

将矩阵放入列表中,然后将其放入 3d 数组并计算平均值:

simplify2array(l) |>
    rowMeans(dims = 2)

其中

l
是您的矩阵列表。

示例数据

set.seed(100)
l <- lapply(1:4, \(i) matrix(rnorm(36), nrow = 3))
© www.soinside.com 2019 - 2024. All rights reserved.