r - Multiplying one matrix with a set of scalars -
i have r script systematically perform changes 3x3 matrix scalar multiplication follows
r <- matrix(rexp(9, rate=.1), ncol=3); (i in 1:360) { k = i*r; ... }
and use modified matrix further calculations within loop. however, loop nested inside 2 other loops, making script slow. question is, how can vectorize innermost loop such result instead three-dimensional array of size 3x3x360 where
a[,,i] = i*r;
for ranging 1 360?
how basic multiplication , reshaping
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
Comments
Post a Comment