如何在 R 中将矩阵与矢量相乘?
我们用矩阵乘以矢量时,输出是一个矢量。假设我们有矩阵 M 和矢量 V,那么它们可以表示为 M%*%V。要理解这个分步相乘,我们可用矢量中的每个值乘以矩阵中的行值,然后找出该相乘之和。
示例 1
M1<-matrix(1:25,nrow=5) M1
输出
[,1] [,2] [,3] [,4] [,5] [1,] 1 6 11 16 21 [2,] 2 7 12 17 22 [3,] 3 8 13 18 23 [4,] 4 9 14 19 24 [5,] 5 10 15 20 25
示例
V1<-1:5 V1 [1] 1 2 3 4 5 M1%*%V1
输出
[,1] [1,] 215 [2,] 230 [3,] 245 [4,] 260 [5,] 275
示例 2
M2<-matrix(1:100,nrow=10) M2
输出
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [1,] 1 11 21 31 41 51 61 71 81 91 [2,] 2 12 22 32 42 52 62 72 82 92 [3,] 3 13 23 33 43 53 63 73 83 93 [4,] 4 14 24 34 44 54 64 74 84 94 [5,] 5 15 25 35 45 55 65 75 85 95 [6,] 6 16 26 36 46 56 66 76 86 96 [7,] 7 17 27 37 47 57 67 77 87 97 [8,] 8 18 28 38 48 58 68 78 88 98 [9,] 9 19 29 39 49 59 69 79 89 99 [10,] 10 20 30 40 50 60 70 80 90 100
示例
V2<-1:10 V2 [1] 1 2 3 4 5 6 7 8 9 10 M2%*%V2
输出
[,1] [1,] 3355 [2,] 3410 [3,] 3465 [4,] 3520 [5,] 3575 [6,] 3630 [7,] 3685 [8,] 3740 [9,] 3795 [10,] 3850
示例 3
M3<-matrix(rnorm(36,5,1),nrow=18) M3
输出
[,1] [,2] [1,] 3.627929 6.929146 [2,] 3.363237 4.400114 [3,] 4.640349 5.089977 [4,] 6.201115 5.483314 [5,] 4.354126 7.024478 [6,] 4.489391 6.631517 [7,] 4.400877 6.370375 [8,] 5.545603 2.586863 [9,] 4.508706 4.145658 [10,] 5.191536 5.562368 [11,] 4.441472 4.634800 [12,] 5.922700 4.657329 [13,] 6.153998 4.224459 [14,] 3.627590 4.987152 [15,] 6.290181 5.699693 [16,] 6.154902 5.031921 [17,] 6.445679 5.216649 [18,] 5.261013 5.407813
示例
V3<-c(5,10) V3 [1] 5 10 M3%*%V3
输出
[,1] [1,] 87.43110 [2,] 60.81733 [3,] 74.10152 [4,] 85.83872 [5,] 92.01541 [6,] 88.76213 [7,] 85.70814 [8,] 53.59664 [9,] 64.00011 [10,] 81.58136 [11,] 68.55536 [12,] 76.18679 [13,] 73.01458 [14,] 68.00947 [15,] 88.44784 [16,] 81.09372 [17,] 84.39489 [18,] 80.38319
示例 4
M4<-matrix(rpois(50,10),ncol=5) M4
输出
[,1] [,2] [,3] [,4] [,5] [1,] 12 2 9 4 14 [2,] 13 12 10 5 13 [3,] 10 8 9 12 9 [4,] 11 9 9 10 11 [5,] 12 11 14 6 8 [6,] 12 5 13 8 13 [7,] 16 11 10 14 10 [8,] 12 11 13 12 6 [9,] 4 7 5 8 10 [10,] 9 14 10 13 15
示例
V4<-1:5 V4 [1] 1 2 3 4 5 M4%*%V4
输出
[,1] [1,] 129 [2,] 152 [3,] 146 [4,] 151 [5,] 140 [6,] 158 [7,] 174 [8,] 151 [9,] 115 [10,] 194
示例
M5<-matrix(sample(0:9,20,replace=TRUE),ncol=5) M5
输出
[,1] [,2] [,3] [,4] [,5] [1,] 5 8 0 7 0 [2,] 9 9 7 8 0 [3,] 9 1 7 0 9 [4,] 6 6 5 7 6
示例
V5<-c(2,4,6,8,10) V5 [1] 2 4 6 8 10 M5%*%V5
输出
[,1] [1,] 98 [2,] 160 [3,] 154 [4,] 182
广告