1
votes

I have a data set with 9200 rows and 6 columns. I found the kernel of this data frame with the following code:

  #kernel
  library("kernlab", "v0.9-27")
  D<-as.matrix(X1)
  rbf <- rbfdot(sigma = 0.05)
  kernel<-kernelMatrix(rbf, D)

Now I want to put this as a diagonal of a square matrix. for example suppose kernel matrix is

    K11  k12
    k21  k22

I need a matrix like

    K11  k12   0    0    0    0    0    0
    k21  k22   0    0    0    0    0    0
    0     0   K11  k12   0    0    0    0
    0     0   k21  k22   0    0    0    0
    0     0    0    0   K11  k12   0    0
    0     0    0    0   K21  k22   0    0
    0     0    0    0    0    0    K11  k12
    0     0    0    0    0    0    K21  k22
2
Matrix::bdiag(replicate(2, kernel, simplify = FALSE))user2957945
I got this error : no method or default for coercing “function” to “CsparseMatrix”sherek_66
sherek_66; well that seems like it is using the stats::kernel function and not the kernel object from your question. Run the code in your question and then the code in the comment ^^ and it will work.user2957945

2 Answers

1
votes

You may have to adjust the dimensions based on your actual need -

# this is your kernel matrix
m1 <- matrix(c("K11","k12","k21","k22"), nrow = 2, ncol = 2, byrow = T)

# this is output matrix; change nrow and ncol as per needs
m2 <- matrix("0", nrow = 8, ncol = 8)

for(i in seq(1, nrow(m2), nrow(m1))) {
  m2[i:(i+nrow(m1)-1), i:(i+nrow(m1)-1)] <- m1
}

m2
     [,1]  [,2]  [,3]  [,4]  [,5]  [,6]  [,7]  [,8] 
[1,] "K11" "k12" "0"   "0"   "0"   "0"   "0"   "0"  
[2,] "k21" "k22" "0"   "0"   "0"   "0"   "0"   "0"  
[3,] "0"   "0"   "K11" "k12" "0"   "0"   "0"   "0"  
[4,] "0"   "0"   "k21" "k22" "0"   "0"   "0"   "0"  
[5,] "0"   "0"   "0"   "0"   "K11" "k12" "0"   "0"  
[6,] "0"   "0"   "0"   "0"   "k21" "k22" "0"   "0"  
[7,] "0"   "0"   "0"   "0"   "0"   "0"   "K11" "k12"
[8,] "0"   "0"   "0"   "0"   "0"   "0"   "k21" "k22"
0
votes

To answer this question in general I would better suggest to use the kronecker product of R base. What it does is simply multiply (as scalar) all the elements of the first matrix by the whole second matrix and converts into a matrix of combined dimension as in your case.

So for instance:

D <- diag(1,4) # Identity matrix, in your case you should change 4 by 6
M <- matrix(1:4, 2, 2) # Matrix 2x2
kronecker(D,M) # Matrix you are looking for
#output

     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
[1,]    1    3    0    0    0    0    0    0
[2,]    2    4    0    0    0    0    0    0
[3,]    0    0    1    3    0    0    0    0
[4,]    0    0    2    4    0    0    0    0
[5,]    0    0    0    0    1    3    0    0
[6,]    0    0    0    0    2    4    0    0
[7,]    0    0    0    0    0    0    1    3
[8,]    0    0    0    0    0    0    2    4