# 数组乘以矩阵中的各个行

array1 <- array(1:108, c(6,6,3))

[,1] [,2] [,3] [,4] [,5] [,6]
[1,]    1    7   13   19   25   31
[2,]    2    8   14   20   26   32
[3,]    3    9   15   21   27   33
[4,]    4   10   16   22   28   34
[5,]    5   11   17   23   29   35
[6,]    6   12   18   24   30   36

, , 2

[,1] [,2] [,3] [,4] [,5] [,6]
[1,]   37   43   49   55   61   67
[2,]   38   44   50   56   62   68
[3,]   39   45   51   57   63   69
[4,]   40   46   52   58   64   70
[5,]   41   47   53   59   65   71
[6,]   42   48   54   60   66   72

, , 3

[,1] [,2] [,3] [,4] [,5] [,6]
[1,]   73   79   85   91   97  103
[2,]   74   80   86   92   98  104
[3,]   75   81   87   93   99  105
[4,]   76   82   88   94  100  106
[5,]   77   83   89   95  101  107
[6,]   78   84   90   96  102  108

matrix1 <- matrix(1:18, nrow = 3, ncol = 6)

[,1] [,2] [,3] [,4] [,5] [,6]
[1,]    1    4    7   10   13   16
[2,]    2    5    8   11   14   17
[3,]    3    6    9   12   15   18

1*1 + 7*4 + 13*7 + 19*10 +25*13 + 31*16 = result

Rows <- min(dim(array1)[1], dim(matrix1)[1])
Cols <- min(dim(array1)[2], dim(matrix1)[2])

apply(array1, 3, function(x) rowSums(matrix1 * x[1:Rows,1:Cols]))

array1[ , , 1] * matrix1 #or array1[1:Rows, 1:Cols, 1] * matrix1

rowSums如其名称所示，给出每一行的总和。因此，阵列中第一个平面的结果与矩阵相乘并汇总为一个向量。

rowSums(array1[1:Rows, 1:Cols, 1] * matrix1)
# 1131 1284 1449

0条评论