将一个矩阵与一组标量相乘
Multiplying one matrix with a set of scalars
我有一个 R 脚本,它通过标量乘法系统地对 3x3 矩阵执行如下更改
R <- matrix(rexp(9, rate=.1), ncol=3);
for (i in 1:360) {
K = i*R;
...
}
并使用修改后的矩阵在循环内进行进一步计算。但是,循环本身嵌套在另外两个 for 循环中,使脚本非常慢。所以我的问题是,我如何向量化这个最内层的循环,使得结果变成一个大小为 3x3x360 的三维数组 A,其中
A[,,i] = i*R;
对于从 1 到 360 的所有 i?
一些基本的乘法和整形怎么样
set.seed(15) #for reproducibility
R <- matrix(rexp(9, rate=.1), ncol=3);
R
# [,1] [,2] [,3]
# [1,] 2.042281 1.760375 2.9230182
# [2,] 19.466458 6.628580 0.1818078
# [3,] 2.544348 27.541514 4.1325714
dd <- array(sapply(1:360, `*`, R), dim=c(dim(R), 360))
dd[,,1]
# [,1] [,2] [,3]
# [1,] 2.042281 1.760375 2.9230182
# [2,] 19.466458 6.628580 0.1818078
# [3,] 2.544348 27.541514 4.1325714
dd[,,2]
# [,1] [,2] [,3]
# [1,] 4.084562 3.520749 5.8460364
# [2,] 38.932916 13.257161 0.3636157
# [3,] 5.088697 55.083027 8.2651427
dd[,,10]
# [,1] [,2] [,3]
# [1,] 20.42281 17.60375 29.230182
# [2,] 194.66458 66.28580 1.818078
# [3,] 25.44348 275.41514 41.325714
我有一个 R 脚本,它通过标量乘法系统地对 3x3 矩阵执行如下更改
R <- matrix(rexp(9, rate=.1), ncol=3);
for (i in 1:360) {
K = i*R;
...
}
并使用修改后的矩阵在循环内进行进一步计算。但是,循环本身嵌套在另外两个 for 循环中,使脚本非常慢。所以我的问题是,我如何向量化这个最内层的循环,使得结果变成一个大小为 3x3x360 的三维数组 A,其中
A[,,i] = i*R;
对于从 1 到 360 的所有 i?
一些基本的乘法和整形怎么样
set.seed(15) #for reproducibility
R <- matrix(rexp(9, rate=.1), ncol=3);
R
# [,1] [,2] [,3]
# [1,] 2.042281 1.760375 2.9230182
# [2,] 19.466458 6.628580 0.1818078
# [3,] 2.544348 27.541514 4.1325714
dd <- array(sapply(1:360, `*`, R), dim=c(dim(R), 360))
dd[,,1]
# [,1] [,2] [,3]
# [1,] 2.042281 1.760375 2.9230182
# [2,] 19.466458 6.628580 0.1818078
# [3,] 2.544348 27.541514 4.1325714
dd[,,2]
# [,1] [,2] [,3]
# [1,] 4.084562 3.520749 5.8460364
# [2,] 38.932916 13.257161 0.3636157
# [3,] 5.088697 55.083027 8.2651427
dd[,,10]
# [,1] [,2] [,3]
# [1,] 20.42281 17.60375 29.230182
# [2,] 194.66458 66.28580 1.818078
# [3,] 25.44348 275.41514 41.325714