我正在将一个MATLAB脚本转换为R,并对此感到遗憾,因为此刻它速度较慢。我试图尽可能多地使用“矢量化函数”,但我对R相对比较陌生,不知道这是什么意思。如果你使用大量的运算符(包括括号),那么从我的循环研究来说,它只比R中的apply()方法慢。否则,我不会看到R可以做些什么来进一步减慢它。这是我想要加速的代码。等效于MATLAB的reshape()方法的最快R?
somPEs <- 9;
inputPEs <- 6;
initial_w <- matrix(1, nrow=somPEs, ncol=inputPEs)
w <- apply(initial_w, 1, function(i) runif(i));
# Reshape w to a 3D matrix of dimension: c(sqrt(somPEs), sqrt(somPEs), inputPEs)
nw <- array(0, dim=c(sqrt(somPEs), sqrt(somPEs), inputPEs))
for (i in 1:inputPEs) {
nw[,,i] <- matrix(w[i,], nrow=sqrt(somPEs), ncol=sqrt(somPEs), byrow=TRUE)
}
w <- nw;
在MATLAB中,该代码是由被称为“重塑”一个内置的功能执行,如按以下步骤进行:
w = reshape(w,[sqrt(somPEs) sqrt(somPEs) inputPEs]);
我计时我的当前R代码,它实际上是超快速,但我仍然想了解矢量化以及如何将我的代码转换为apply()以提高可读性。
user system elapsed
0.003 0.000 0.002