In MATLAB, there is a constructor `diagm`

for block diagonal matrices.

I seem to recall that this is missing in Julia. If I am wrong, what is the most elegant way to create one?

In MATLAB, there is a constructor `diagm`

for block diagonal matrices.

I seem to recall that this is missing in Julia. If I am wrong, what is the most elegant way to create one?

1 Like

for sparse matrices, there is `SparseArrays.blockdiag`

1 Like

There’s also BlockDiagonals.jl I have not used that package myself, but it looks useful.

However, packages like BlockBandedMatrices and BlockDiagonals do not create Matlab-style matrices, but instead define new types to hold diagonal matrices. That can make some operations (such as matrix-matrix or matrix-vector multiplication) run faster, but also means that some things that are possible in Matlab (such as adding entries outside of the blocks) won’t work.

`SparseArrays.blockdiag(...)`

gives basically the same thing as `sparse(blkdiag(..))`

would give in Matlab.

For a plain-vanilla Julia matrix, just use any of the above, and then pass the result to the `Matrix`

constructor. This is the most Matlab-like option, but therefore it will also be as slow and as memory-consuming as Matlab.

1 Like