加快这个棘手的矩阵计算

时间:2013-06-10 16:17:39

标签: 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_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 

1 个答案:

答案 0 :(得分:0)

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