How to create a matrix of matrix in Julia (or an Array{Float64,2} of an Array{Float64,2})?

Viewed 65

So, I need a matrix A to be (2,2) in dimension (2 rows and 2 columns) and I need every element to contain a (3,3) matrix. Basically, I want to store something like this:

A[1,1] = rand(3,3);
A[1,2] = rand(3,3);
A[2,1] = rand(3,3);
A[2,2] = radn(3,3);

How can I initialize this array?

I tried a lot of ways but neither works, and I can't still find anything pointing me in the right direction. I will appreciate any help you can provide! Thanks in advance and stay safe!

1 Answers

Just do:

julia> a = [rand(3,3) for i in 1:2, j in 1:2]
2×2 Matrix{Matrix{Float64}}:
 [0.053357 0.711579 0.75664; 0.845828 0.636514 0.320966; 0.602228 0.711782 0.621663]   [0.699139 0.18294 0.589273; 0.394751 0.58442 0.338332; 0.877285 0.195956 0.684808]
 [0.636646 0.549331 0.143829; 0.689687 0.625455 0.932277; 0.304346 0.479196 0.172392]  [0.749814 0.165602 0.116884; 0.120514 0.791254 0.0774126; 0.481224 0.534405 0.0506928]

If you rather need an uninitialized matrix than you can do:

julia> m = Matrix{Matrix{Float64}}(undef, 2, 2)
2×2 Matrix{Matrix{Float64}}:
 #undef  #undef
 #undef  #undef

julia> m[1,1] = rand(3,3); m
2×2 Matrix{Matrix{Float64}}:
    [0.319113 0.791794 0.834767; 0.785798 0.861869 0.948621; 0.754274 0.474736 0.758176]  #undef
 #undef                                                                                   #undef
Related