Hi, I am trying to write a function to produce a Kernel matrix K(i,j) using an n-element vector x and cosntant rho.
Please could someone assist with why me output is showing as NULL when coding the following? (NB the rho of 2 and n of 6 are chosen arbitrarily and I want the function to work given any rho or n).
rho <- 2
x <- c(1,2,3,4,5,6)
n <- length(x)
kernel.matrix <- function(x, rho) {
for(i in 1:n)
for (j in 1:n)
{exp(-(((x[i]-x[j])^2)/(rho^2)))}
}
You are not storing the results of exp(-(((x[i]-x[j])^2)/(rho^2))) anywhere. Try something like this.
rho <- 2
x <- c(1,2,3,4,5,6)
n <- length(x)
kernel.matrix <- function(x, rho) {
MAT <- matrix(rep(0,n^2),nrow=n)
for(i in 1:n)
for (j in 1:n) {
MAT[i,j] <- exp(-(((x[i]-x[j])^2)/(rho^2)))
}
MAT
}
K <- kernel.matrix(x, rho)
K