R 加速这个复杂的矩阵计算

R 加速这个复杂的矩阵计算,r,matrix,R,Matrix,到目前为止,我正在从一个大型矩阵计算一些特性,并在for循环中完成所有工作。正如所料,速度非常慢。我已经能够对代码的一部分进行矢量化,但有一部分被卡住了 我将非常感谢您的建议/帮助 s1 <- MyMatrix #dim = c(5167,256) fr <- MyVector #vector of length 256 tw <- 5 fw <- 6 # For each point S(t,f) we need the sub-matrix of points S

到目前为止,我正在从一个大型矩阵计算一些特性,并在for循环中完成所有工作。正如所料,速度非常慢。我已经能够对代码的一部分进行矢量化,但有一部分被卡住了

我将非常感谢您的建议/帮助

s1 <- MyMatrix #dim = c(5167,256)
fr <- MyVector #vector of length 256

tw <- 5
fw <- 6

# For each point S(t,f) we need the sub-matrix of points S_hat(i,j),
# i in [t - tw, t + tw], j in [f - fw, f + fw] for the feature vector.
# To avoid edge effects, I pad the original  matrix with zeros,
# resulting in a matrix of size nobs+2*tw x nfreqs+2*fw
nobs <- dim(s1)[1] #note: this is 5167
nf <- dim(s1)[2]   #note: this is 256
sp <- matrix(0, nobs+2*tw, nf+2*fw)
t1 <- tw+1; tn <- nobs+tw
f1 <- fw+1; fn <- nf+fw
sp[t1:tn, f1:fn] <- s1 # embed the actual matrix into the padding

nfeatures <- 1 + (2*tw+1)*(2*fw+1) + 1
fsp <- array(NaN, c(dim(sp),nfeatures))
for (t in t1:tn){
  for (f in f1:fn){
    fsp[t,f,1] <- fr[(f - f1 + 1)] #this part I can vectorize 
    fsp[t,f,2:(nfeatures-1)] <- as.vector(sp[(t-tw):(t+tw),(f-fw):(f+fw)]) #this line is the problem
    fsp[t,f,nfeatures] <- var(fsp[t,f,2:(nfeatures-1)])
  }
}

fspec[t1:tn, f1:fn, 1] <- t(matrix(rep(fr,(tn-t1+1)),ncol=(tn-t1+1)))
#vectorized version of the first feature  ^

return(fsp[t1:tn, f1:fn, ]) #this is the returned matrix 

s1我假设第二个特征矢量化后,var特征将很容易矢量化

看起来有很多未使用的“层”,即对于给定的
n特征值
,所有
fsp[1:t1,1:f1,]
都不会在循环中使用。根据事物的大小,这可能很重要。接下来,您确定将
var(fsp[…])
计算矢量化没有帮助吗?