Reputation: 29
I know how I can make an array of N numbers of p*p matrices:
m=array(x, c(p,p,N))
which x
could be a vector or a scalar. I want to make an array of diagonal matrices. Each matrix should be diagonal. I tried several ways but they don't work. Does anyone know about it?
Upvotes: 3
Views: 497
Reputation: 132676
If you don't mind using a package, you could use abind
:
library(abind)
do.call(abind, c(rep(list(diag(3)), 2), along = 3))
#, , 1
#
# [,1] [,2] [,3]
#[1,] 1 0 0
#[2,] 0 1 0
#[3,] 0 0 1
#
#, , 2
#
# [,1] [,2] [,3]
#[1,] 1 0 0
#[2,] 0 1 0
#[3,] 0 0 1
Upvotes: 2
Reputation: 31161
It's a little bit clumsy but you can do this:
n = 3
num_of_matrix = 2
array(rep(c(diag(n)),num_of_matrix),c(n,n,num_of_matrix))
#, , 1
# [,1] [,2] [,3]
#[1,] 1 0 0
#[2,] 0 1 0
#[3,] 0 0 1
#, , 2
# [,1] [,2] [,3]
#[1,] 1 0 0
#[2,] 0 1 0
#[3,] 0 0 1
Upvotes: 4