我是R的初学者,当我诉诸for
循环时,我总觉得我没有很好地使用这门语言。
我想在大矩阵上优化度量的计算,最好不使用循环。这是我的尝试:
ComputeVariance <- function(x, Delta, WindowSize, type){
# Compute GramMatrix
GramMatrix = outer(x, x, Kernel, Delta, type)
Variance = vector("numeric", length(x))
# Index of the points to compute the variance on these points
Index = seq(WindowSize/2, length(x) - WindowSize, by = WindowSize)
for (i in Index){
# Extraction of the sub-matrix useful to computations
SubMat=GramMatrix[(i - WindowSize/2 + 1):(i + WindowSize/2),(i - WindowSize/2 + 1):(i + WindowSize/2)]
SubMatWithoutDiag = SubMat - diag(diag(SubMat))
Variance[i] = sum(diag(SubMat))/WindowSize - sum(apply(SubMatWithoutDiag, 1, sum))/(WindowSize*(WindowSize - 1))
}
return(Variance)
}