I am trying to make a diagonal block matrix in Julia. I have an nxn
array that I want to make P
copies of as a block matrix down the diagonal and the rest of the matrix is sparse.
If arr
is my array, I know I can use:
blockdiag(sparse(arr),sparse(arr))
to create a block with P=2 copies of the array down the diagonal.
However, for large P, how can I do this in a general way with variable P
?
I tried making an array that is (nxnxP
), however BlockDiag()
does not accept a 3D array.
fill
can repeat elements without actually making a copy.
Hence you can just do:
blockdiag(fill(sparse(arr), 2)...)
Here is a full Julia session:
julia> using SparseArrays
julia> arr=Matrix(sprand(Float64,3,3,0.25))
3×3 Matrix{Float64}:
0.0 0.016897 0.0
0.219705 0.0 0.0
0.0 0.0 0.893547
julia> blockdiag(fill(sparse(arr), 2)...)
6×6 SparseMatrixCSC{Float64, Int64} with 6 stored entries:
⋅ 0.016897 ⋅ ⋅ ⋅ ⋅
0.219705 ⋅ ⋅ ⋅ ⋅ ⋅
⋅ ⋅ 0.893547 ⋅ ⋅ ⋅
⋅ ⋅ ⋅ ⋅ 0.016897 ⋅
⋅ ⋅ ⋅ 0.219705 ⋅ ⋅
⋅ ⋅ ⋅ ⋅ ⋅ 0.893547