0

I have a 2X2 matrix, for instance A=matrix(1:4,2,2). With this matrix, I want to build matrix whose diagonal element is A like below. This example has just three A but I would like to make matrix with n diagonal element of matrix A

|A  0  0|
|0  A  0|
|0  0  A|
rawr
  • 20,481
  • 4
  • 44
  • 78
John legend2
  • 840
  • 9
  • 18
  • see Matrix package... `bdiag`: `bdiag(rep(list(A), 3))` – user20650 Apr 10 '16 at 02:41
  • `n <- 3; nr <- nrow(A); ii <- vapply(1:n, function(x) row(A) + (x - 1L) * nr, integer(nr ^ 2)); \`[<-\`(matrix(0, nr * n, nr * n), cbind(c(ii), sort(ii)), rep(A, n))` will work for square matrices. – rawr Apr 10 '16 at 04:34

2 Answers2

0

Here is a recursive solution:

CreateDiag<-function(n){
 if (n==1) {
    return(A)
 } else{
    A_2<-CreateDiag(n-1)
    temp1<-cbind(A_2,matrix(0,nrow = nrow(A_2),ncol = ncol(A)))
    temp2<-rbind(temp1,cbind(matrix(0,nrow = nrow(A),ncol = ncol(A_2)),A))
    return(temp2)
 }
}

(n is the number of blocks you want)

adaien
  • 1,932
  • 1
  • 12
  • 26
0
> DiagonalMatrix <- function(n, x) `diag<-`(matrix(0, n, n), x)
> DiagonalMatrix(2, 10)
     [,1] [,2]
[1,]   10    0
[2,]    0   10
hatmatrix
  • 42,883
  • 45
  • 137
  • 231