Fast calculation of the kernel matrix in R

I have an nx p-matrix and would like to compute an nx n-matrix B defined as

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

where f is a function that takes arguments of the corresponding dimension. Is there a neat trick to figure this out in R? f is symmetric and positive definite (if this can help with the calculation).

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

+6
source share
1 answer

You can use outer with matrix sizes.

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

Source: https://habr.com/ru/post/946601/


All Articles