如何在 R 中将两个矩阵合并创建为一个块对角矩阵?
块对角矩阵是指一个矩阵被添加到另一个矩阵的末尾元素。例如,如果我们有一个包含九个值的矩阵,而另一个矩阵也有九个值,那么第二个矩阵将被添加到第一个矩阵中,并且第一个矩阵下面的元素将为零,而第二个矩阵上面的元素也将为零。
示例
M1<-matrix(1:9,ncol=3) M1
输出
[,1] [,2] [,3] [1,] 1 4 7 [2,] 2 5 8 [3,] 3 6 9
示例
M2<-matrix(10:18,ncol=3) M2
输出
[,1] [,2] [,3] [1,] 10 13 16 [2,] 11 14 17 [3,] 12 15 18
示例
rbind(cbind(M1,matrix(0,nrow=nrow(M1),ncol=ncol(M2))),cbind(matrix(0,nrow=nrow(M2),ncol=ncol(M1)),M2))
输出
[,1] [,2] [,3] [,4] [,5] [,6] [1,] 1 4 7 0 0 0 [2,] 2 5 8 0 0 0 [3,] 3 6 9 0 0 0 [4,] 0 0 0 10 13 16 [5,] 0 0 0 11 14 17 [6,] 0 0 0 12 15 18
示例
M3<-matrix(1:25,nrow=5) M3
输出
[,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
示例
M4<-matrix(26:50,ncol=5) M4
输出
[,1] [,2] [,3] [,4] [,5] [1,] 26 31 36 41 46 [2,] 27 32 37 42 47 [3,] 28 33 38 43 48 [4,] 29 34 39 44 49 [5,] 30 35 40 45 50
示例
rbind(cbind(M3,matrix(0,nrow=nrow(M4),ncol=ncol(M4))),cbind(matrix(0,nrow=nrow(M4),ncol=ncol(M3)),M4))
输出
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [1,] 1 6 11 16 21 0 0 0 0 0 [2,] 2 7 12 17 22 0 0 0 0 0 [3,] 3 8 13 18 23 0 0 0 0 0 [4,] 4 9 14 19 24 0 0 0 0 0 [5,] 5 10 15 20 25 0 0 0 0 0 [6,] 0 0 0 0 0 26 31 36 41 46 [7,] 0 0 0 0 0 27 32 37 42 47 [8,] 0 0 0 0 0 28 33 38 43 48 [9,] 0 0 0 0 0 29 34 39 44 49 [10,] 0 0 0 0 0 30 35 40 45 50
示例
M5<-matrix(sample(1:5,25,replace=TRUE),nrow=5)M5
输出
[,1] [,2] [,3] [,4] [,5] [1,] 2 2 3 1 2 [2,] 2 4 1 5 4 [3,] 4 1 5 4 2 [4,] 2 4 4 2 5 [5,] 5 1 2 5 3
示例
M6<-matrix(sample(6:10,25,replace=TRUE),ncol=5) M6
输出
[,1] [,2] [,3] [,4] [,5] [1,] 10 9 9 6 6 [2,] 8 7 10 9 8 [3,] 8 9 9 8 9 [4,] 7 8 6 8 7 [5,] 8 9 6 8 7
示例
rbind(cbind(M5,matrix(0,nrow=nrow(M6),ncol=ncol(M6))),cbind(matrix(0,nrow=nrow(M6),ncol=ncol(M5)),M6))
输出
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [1,] 3 1 3 1 3 0 0 0 0 0 [2,] 4 2 3 1 5 0 0 0 0 0 [3,] 5 4 3 5 4 0 0 0 0 0 [4,] 1 3 5 1 5 0 0 0 0 0 [5,] 1 2 2 4 5 0 0 0 0 0 [6,] 0 0 0 0 0 8 8 7 6 10 [7,] 0 0 0 0 0 6 6 8 10 7 [8,] 0 0 0 0 0 9 6 7 10 9 [9,] 0 0 0 0 0 10 6 10 6 7 [10,] 0 0 0 0 0 10 10 9 7 6
示例
M7<-matrix(round(rnorm(36),0),nrow=6) M7
输出
[,1] [,2] [,3] [,4] [,5] [,6] [1,] 1 0 2 -1 1 0 [2,] -2 0 2 0 0 -1 [3,] -1 0 0 0 0 0 [4,] 0 0 1 1 1 0 [5,] 1 -1 0 -1 2 1 [6,] 0 1 0 0 2 -1
示例
M8<-matrix(round(runif(36,2,5),0),nrow=6) M8
输出
[,1] [,2] [,3] [,4] [,5] [,6] [1,] 3 4 3 3 3 4 [2,] 2 2 2 3 4 5 [3,] 3 2 3 4 4 3 [4,] 3 3 5 2 3 2 [5,] 3 5 4 4 5 2 [6,] 4 2 2 4 2 3
示例
rbind(cbind(M7,matrix(0,nrow=nrow(M8),ncol=ncol(M8))),cbind(matrix(0,nrow=nrow(M8),ncol=ncol(M7)),M8))
输出
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12] [1,] 0 0 0 1 -1 1 0 0 0 0 0 0 [2,] -1 1 2 1 -1 1 0 0 0 0 0 0 [3,] 0 0 1 0 1 1 0 0 0 0 0 0 [4,] -1 0 -2 0 1 -3 0 0 0 0 0 0 [5,] 0 1 1 0 1 0 0 0 0 0 0 0 [6,] 0 0 0 0 0 1 0 0 0 0 0 0 [7,] 0 0 0 0 0 0 2 4 2 2 3 4 [8,] 0 0 0 0 0 0 4 4 5 3 3 4 [9,] 0 0 0 0 0 0 3 5 3 4 5 3 [10,] 0 0 0 0 0 0 3 4 5 4 2 5 [11,] 0 0 0 0 0 0 4 3 3 3 4 2 [12,] 0 0 0 0 0 0 5 3 5 2 3 5
广告