I have tried to write a function with a double loop, because I have to simulate a double sum. This code My code works but it is slow, how can I speed it up?
a & y are vectors, x is a matrix. They are all the same length, namely 100. X is 100x4 (100 rows, 4 col)
X1 <- matrix(rnorm(4*100), ncol=4)
y1 <- sign(X1[,1] + X1[,2] > 0)*2 - 1
fn <- function (a,x,y){
dsum <-0
for(i in 1:length(y)){
for(j in 1:length(y)){
dsum <- dsum + a[j]*a[i]*y[j]*y[i]*(t(x)[,j])%*%x[i,]
}
}
res <- sum(a)-.5*dsum
return (res)
}
I tried to do sum(a)-.5%*%sum(a%o%X%o%y*a%o%t(X)%o%y)
But I am most certainly wrong.