Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize a Matrix of Matrices with the right dimension?

Tags:

julia

I would like to create a n x m-dimension Matrix of k x k-dimension Matrices (containing zeros).

How can I do that in Julia?

like image 262
RangerBob Avatar asked Dec 04 '25 21:12

RangerBob


1 Answers

n-d comprehensions are probably easiest:

[zeros(k,k) for i=1:n, j=1:m]

Update: You need to be careful here: presumably you want to fill the array with different matrices of zeros: the other proposed solutions (fill or repmat) will actually give you an array where all the entries are the same zeros matrix, e.g.:

julia> k = 2; n = 3; m = 4; A = fill(zeros(k, k), n, m)
3×4 Array{Array{Float64,2},2}:
 [0.0 0.0; 0.0 0.0]  [0.0 0.0; 0.0 0.0]  [0.0 0.0; 0.0 0.0]  [0.0 0.0; 0.0 0.0]
 [0.0 0.0; 0.0 0.0]  [0.0 0.0; 0.0 0.0]  [0.0 0.0; 0.0 0.0]  [0.0 0.0; 0.0 0.0]
 [0.0 0.0; 0.0 0.0]  [0.0 0.0; 0.0 0.0]  [0.0 0.0; 0.0 0.0]  [0.0 0.0; 0.0 0.0]

julia> A[1,1][1,1] = 1; A
3×4 Array{Array{Float64,2},2}:
 [1.0 0.0; 0.0 0.0]  [1.0 0.0; 0.0 0.0]  [1.0 0.0; 0.0 0.0]  [1.0 0.0; 0.0 0.0]
 [1.0 0.0; 0.0 0.0]  [1.0 0.0; 0.0 0.0]  [1.0 0.0; 0.0 0.0]  [1.0 0.0; 0.0 0.0]
 [1.0 0.0; 0.0 0.0]  [1.0 0.0; 0.0 0.0]  [1.0 0.0; 0.0 0.0]  [1.0 0.0; 0.0 0.0]
like image 114
Simon Byrne Avatar answered Dec 07 '25 15:12

Simon Byrne