user2458552
user2458552

Reputation: 419

Storing matrices in an array in R

How can I store matrices of same dimension in R? That is If I have an array(say,mat) of 3 matrices ,say,A,B,C

mat[1] gives me matrix A.

I need this as I need to run a loop using the array mat.

Upvotes: 0

Views: 311

Answers (2)

nograpes
nograpes

Reputation: 18323

Arrays and matrices are essentially the same thing in R. If all of your matrices are the same size, then use a 3-d matrix. If they are not, then use a list.

Upvotes: 1

Roland
Roland

Reputation: 132676

A <- matrix(1:4,2)
B <- matrix(5:8,2)
C <- matrix(9:12,2)

array(c(A,B,C),dim=c(2,2,3))

# , , 1
# 
#      [,1] [,2]
# [1,]    1    3
# [2,]    2    4
# 
# , , 2
# 
#      [,1] [,2]
# [1,]    5    7
# [2,]    6    8
# 
# , , 3
# 
#      [,1] [,2]
# [1,]    9   11
# [2,]   10   12

Upvotes: 2

Related Questions