简体   繁体   中英

Fast computation of kernel matrix in R

I have an nxp matrix and would like to compute the nxn matrix B defined as

B[i, j] = f(A[i,], A[j,])

where f is a function that accepts arguments of the appropriate dimensionality. Is there a neat trick to compute this in R? f is symmetric and positive-definite (if this can help in the computation).

EDIT: Praneet asked to specify f. That is a good point. Although I think it would be interesting to have an efficient solution for any function, I would get a lot of mileage from efficient computation in the important case where f(x, y) is base::norm(xy, type='F').

You can use outer with the matrix dimensions.

n <- 10
p <- 5
A <- matrix( rnorm(n*p), n, p )
f <- function(x,y) sqrt(sum((x-y)^2))
B <- outer( 
  1:n, 1:n, 
  Vectorize( function(i,j) f(A[i,], A[j,]) ) 
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM