Reputation: 457
I have data from three axes of a physical object in 3 separate vectors.
x;y;z
[1] 4 6 4 6 17 10 13 27 33 19
[1] 3 2 5 13 22 20 23 19 31 14
[1] 21 6 12 35 19 44 34 23 26 33
I want to combine these three vectors into a 3-dimensional matrix (if that exist in R) by simply taking the product of them all. If I had just two axes, say "x" and "y" I could do the following
outer(x, y, FUN="*")
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] 12 8 20 52 88 80 92 76 124 56
[2,] 18 12 30 78 132 120 138 114 186 84
[3,] 12 8 20 52 88 80 92 76 124 56
[4,] 18 12 30 78 132 120 138 114 186 84
[5,] 51 34 85 221 374 340 391 323 527 238
[6,] 30 20 50 130 220 200 230 190 310 140
[7,] 39 26 65 169 286 260 299 247 403 182
[8,] 81 54 135 351 594 540 621 513 837 378
[9,] 99 66 165 429 726 660 759 627 1023 462
[10,] 57 38 95 247 418 380 437 361 589 266
But, because I have three axes, I am not sure how to do this. Using outer on "x" & "y" and then multiplying that by "z" is not the same as using outer on "x" & "z" and multiplying by "y". The goal after generating the 3D matrix is to then plot the 3D matrix.
I have looked at some other posts like this one, but find it confusing Creating a 3D matrix with R?
Upvotes: 1
Views: 439
Reputation: 887691
We can use outer
with Reduce
after placing the vector
s in a list
.
res1 <- Reduce(outer, list(x,y,z))
Or another option is expand.grid
with rowProds
from library(matrixStats)
and then convert the product vector ('v1') into an array
.
library(matrixStats)
v1 <- rowProds(as.matrix(expand.grid(x,y,z)))
res2 <- array(v1, dim=c(length(x), length(y), length(z)))
identical(res1, res2)
#[1] TRUE
dim(res2)
#[1] 10 10 10
x <- c(4, 6, 4, 6, 17, 10, 13, 27, 33, 19)
y <- c(3, 2, 5, 13, 22, 20, 23, 19, 31, 14)
z <- c(21, 6, 12, 35, 19, 44, 34, 23, 26, 33)
Upvotes: 2