smooth <- function(x, probs, bandwidth=5) {
probs = probs/(2*bandwidth)
bins <- numeric(0)
for(num in x) { # find the bins
bins = c(bins, num-bandwidth, num+bandwidth)
}
bins = unique(sort(bins))
newProbs = numeric(length(bins))
for(i in 1:length(x)) {
range = c(match(x[i] - bandwidth, bins), match(x[i] + bandwidth, bins))
for(j in range[1]:(range[2]-1)) {
newProbs[j] = newProbs[j] + probs[i]
}
}
newProbs = append(0, newProbs)
bins = append(x[1]-bandwidth, bins)
plot(bins, newProbs, ylim=c(0,max(newProbs)), type='s',
ylab="f(x)", xlab="x", main=paste("bw =", bandwidth)) # kernel plot
}
x = c(-7, -5, -3, -1, 1, 3, 5)
probs = c(0.12, 0.16, 0.24, 0.12, 0.08, 0.16, 0.12)
layout(matrix(c(1,2,3,4), nrow=2, ncol=2, byrow=TRUE))
plot(x, probs, ylim=c(0, max(probs)), ylab="p(x)", main="Sequential vs Global") # initial plot
smooth(x, probs, bandwidth=1) # plot for bandwidth = 1
smooth(x, probs, bandwidth=3) # plot for bandwidth = 3
smooth(x, probs, bandwidth=5) # plot for bandwidth = 5

x = c(-9, -5, -3, -1, 1, 3, 5, 7, 9)
probs = c(1/25, 2/25, 5/25, 3/25, 4/25, 2/25, 1/25, 3/25, 4/25)
layout(matrix(c(1,2,3,4), nrow=2, ncol=2, byrow=TRUE))
plot(x, probs, ylim=c(0, max(probs)), ylab="p(x)", main="Active vs Reflective") # initial plot
smooth(x, probs, bandwidth=1) # plot for bandwidth = 1
smooth(x, probs, bandwidth=3) # plot for bandwidth = 3
smooth(x, probs, bandwidth=5) # plot for bandwidth = 5
