What about:
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
}
Then
> 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
or
> 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
You can also specify it by default if you basically want the square matrix to be output:
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
}
Then it expandMatrix(A, 8)will be enough.