Reputation: 19
I am a beginner in R and i know the way i have done is wrong and slow. I would like to fill a matrix and i need to compute each term. I have tried two for loops, here is the code. Do you know a better way to do it?
KernelGaussianMatrix <- function(x,delta){
Mat = matrix(0,nrow=length(x),ncol=length(x))
for (i in 1:length(x)){
for (j in 1:length(x)){
Mat[i,j] = KernelGaussian(x[i],x[j],delta)
}
}
return(Mat)
}
Thx
Upvotes: 1
Views: 1220
Reputation: 10203
you want to use the function outer
as in:
Mat <- outer(x,x,KernelGaussian,delta)
note that any arguments after the third argument in outer
are provided as additional arguments to the function provided as the third argument to outer
Upvotes: 2
Reputation: 17647
If a for loop is required to generate the values than your method is fine.
If the values are already in an array values
you can try mat = matrix(values, nrow=n, ncol=p)
or something similar.
Upvotes: 0