Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create a matrix in `R` and each element in that matrix is another matrix

Tags:

r

Is there a way to create a matrix in R and each element in that matrix is another matrix? I used to do that in Python, but when I do

X <- matrix(rep(0,200),nrow=200,ncol=1)
for (i in 1:200){ X[i,] <-matrix(rep(0,32),nrow=8,ncol=4)}

It is not working in R.

Thanks!

like image 504
Nan Avatar asked Nov 29 '18 16:11

Nan


2 Answers

You may use

X <- matrix(vector("list", 200))

which is just

X <- matrix(list()[rep(1, 200)], nrow = 200, ncol = 1)

with

for (i in 1:200)
  X[i, ] <- list(matrix(rep(0,32), nrow = 8, ncol = 4))

or

for (i in 1:200)
  X[i, ][[1]] <- matrix(rep(0,32), nrow = 8, ncol = 4)

Then each matrix entry will be a list containing a matrix.

like image 167
Julius Vainora Avatar answered Oct 23 '22 03:10

Julius Vainora


If all the submatrices are the same shape, you could use an array:

X = array(0, dim = c(200, 8, 4))

Here are some dimensions

> dim(X)
[1] 200   8   4
> dim(X[1,,])
[1] 8 4
like image 42
mickey Avatar answered Oct 23 '22 03:10

mickey