 Writing a function to produce a matrix

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)))}
}

K <- kernel.matrix(x, rho)
K

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
1 Like

Oh of course, how did I miss that! Thank you.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.