For two given vectors, not necessairly the same length, $x=(x_1,\dots,x_N)$ and $s=(s_1,\dots,s_M)$ I would like to compute the following term as efficiently as possible in R. For $j=1, \dots, N$
$$ H_j:=\sum_{i=1}^Ml_i(x_j)$$ where $$l_i(x_j)= \prod_{l = 1,l \not= j}^M \frac{x_j-s_l}{s_i-s_l}$$
below is some test code which is very inefficient. Howeve, I dont see how I can speed this up using vectorized style or another smart trick.
x <- rnorm(1000)
s <- rnorm(10,2,0.2)
l <- rep(0,length(s))
output <- rep(0,length(x))
for(j in 1:length(x)){
xj <- x[j]
for(i in 1:length(s)){
s.i.dropped <- s[-i]
l[i] <- prod((xj-s.i.dropped)/(s[i]-s.i.dropped))
}
output[j] <- sum(l)
}