我有一个矩阵A,它是:
A <- matrix(c(1:15), byrow=T, nrow=5)
A
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 4 5 6
[3,] 7 8 9
[4,] 10 11 12
[5,] 13 14 15
现在我要创建一个矩阵B,它是8x8维(或10x10,或15x15等),看起来像这样:
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
[1,] 1 2 3 0 0 0 0 0
[2,] 4 5 6 0 0 0 0 0
[3,] 7 8 9 0 0 0 0 0
[4,] 10 11 12 0 0 0 0 0
[5,] 13 14 15 0 0 0 0 0
[6,] 0 0 0 0 0 0 0 0
[7,] 0 0 0 0 0 0 0 0
[8,] 0 0 0 0 0 0 0 0
所以从A开始,我想将列和行添加到8x8维度,全部替换为零值... 任何的想法? 提前谢谢!!
答案 0 :(得分:6)
另一种方法是首先创建更大的矩阵,然后将小的矩阵插入,如此函数:
expandR = function(m,nrows,ncols,with=0){
p=matrix(with,nrows,ncols)
p[1:nrow(m),1:ncol(m)]=m
p
}
不确定哪个更好(更快,更清洁等)。如果您尝试扩展到比原始尺寸小的尺寸,则会导致错误。
答案 1 :(得分:3)
尝试此假设A
至少有一行和一列:
B <- matrix(0, 8, 8)
B[1:nrow(A), 1:ncol(A)] <- A
或作为单一陈述:
B <- "[<-"(matrix(0, 8, 8), 1:nrow(A), 1:ncol(A), value = A)
如果A
可以包含零行或零列,则使用seq_len(nrow(A))
和seq_len(ncol(A))
代替1:nrow(A)
和1:ncol(A)
。
或者,即使在A具有零行或列的情况下,这仍然有效:
B <- matrix(0, 8, 8)
B[cbind(c(row(A)), c(col(A)))] <- A
或
B <- "[<-"(matrix(0, 8, 8), cbind(c(row(A)), c(col(A))), value = A)
或
B <- replace(matrix(0, 8, 8), cbind(c(row(A)), c(col(A))), A)
答案 2 :(得分:1)
怎么样:
A <- matrix(c(1:15), byrow=T, nrow=5)
expandMatrix <- function(X, nrow, ncol) {
X <- cbind(X, matrix(0, nrow = nrow(X), ncol = ncol - ncol(X)))
X <- rbind(X, matrix(0, nrow = nrow - nrow(X), ncol = ncol(X)))
X
}
然后
> expandMatrix(A, 8, 8)
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
[1,] 1 2 3 0 0 0 0 0
[2,] 4 5 6 0 0 0 0 0
[3,] 7 8 9 0 0 0 0 0
[4,] 10 11 12 0 0 0 0 0
[5,] 13 14 15 0 0 0 0 0
[6,] 0 0 0 0 0 0 0 0
[7,] 0 0 0 0 0 0 0 0
[8,] 0 0 0 0 0 0 0 0
或
> expandMatrix(A, 10, 10)
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] 1 2 3 0 0 0 0 0 0 0
[2,] 4 5 6 0 0 0 0 0 0 0
[3,] 7 8 9 0 0 0 0 0 0 0
[4,] 10 11 12 0 0 0 0 0 0 0
[5,] 13 14 15 0 0 0 0 0 0 0
[6,] 0 0 0 0 0 0 0 0 0 0
[7,] 0 0 0 0 0 0 0 0 0 0
[8,] 0 0 0 0 0 0 0 0 0 0
[9,] 0 0 0 0 0 0 0 0 0 0
[10,] 0 0 0 0 0 0 0 0 0 0
如果你主要想要方矩阵作为输出,也可以给它一个默认值:
expandMatrix <- function(X, nrow, ncol = nrow) {
X <- cbind(X, matrix(0, nrow = nrow(X), ncol = ncol - ncol(X)))
X <- rbind(X, matrix(0, nrow = nrow - nrow(X), ncol = ncol(X)))
X
}
然后expandMatrix(A, 8)
就足够了。