Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fast computation of kernel matrix in R

Tags:

r

matrix

I have an n x p matrix and would like to compute the n x n 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(x-y, type='F').

like image 683
gappy Avatar asked Jun 05 '13 15:06

gappy


1 Answers

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,]) ) 
)
like image 184
Vincent Zoonekynd Avatar answered Oct 15 '22 18:10

Vincent Zoonekynd