First of all, here's how I parsed the question:
Problem: turn {n matrices of i rows and j columns} into {i
matrices of n rows and j columns}
Constraint: row x of new matrix y equals row y in old matrix
x
Below is my suggested, generalized, solution (with lower dimensions than
in the presented question, for the sake of presentation). The result is
the same as @ANG's answer, but we can avoid writing out the for
loop,
and have to do less manual work writing out the original matrices.
n <- 3 # number of old matrices
i <- 5 # number of rows in old matrices
j <- 4 # number of columns in old matrices
# Create a list containing the original matrices.
old_matrices <- lapply(seq_len(n), matrix, nrow = i, ncol = j)
# Paste all the original matrices together by column.
m <- do.call(cbind, old_matrices)
Each row of the big matrix m
now represents a single new matrix, with
its rows concatenated together to form a vector.
# Construct the new matrices from the rows in the big matrix.
new_matrices <- tapply(m, row(m), matrix, nrow = n, byrow = T)
And then some checks to make sure we did what we were supposed to:
new_matrices[[1]]
#> [,1] [,2] [,3] [,4]
#> [1,] 1 1 1 1
#> [2,] 2 2 2 2
#> [3,] 3 3 3 3
# Check that there's the right number of new matrices
length(new_matrices) == i
#> [1] TRUE
# Check that the new matrices all have the correct dimensions
all(vapply(new_matrices, function(m) all.equal(dim(m), c(n, j)), logical(1)))
#> [1] TRUE
# Check that the constraint holds
all(vapply(seq_along(new_matrices), function(y) {
vapply(seq_along(old_matrices), function(x) {
all.equal(new_matrices[[y]][x, ], old_matrices[[x]][y, ])
}, logical(1))
}, logical(n)))
#> [1] TRUE