Custom StaticArray matrix type constructors from sub-arrays of a larger matrix type

You can have a lot of flexibility if you use a mutable static matrix as an intermediate local to the function:

julia> function newm(::Val{N}, m::SMatrix{M,M,T}) where {N,M,T}
           a = zeros(MMatrix{N,N,T})
           for i in 1:N
               a[i,i] = one(T)
           end
           a[1:M,1:M] .= m
           return SMatrix{N,N,T}(a)
       end
newm (generic function with 1 method)

julia> newm(Val(4), m)
4×4 SMatrix{4, 4, Int64, 16} with indices SOneTo(4)×SOneTo(4):
 1  4  7  0
 2  5  8  0
 3  6  9  0
 0  0  0  1

julia> @btime newm(Val(4), $m)
  11.524 ns (0 allocations: 0 bytes)
4×4 SMatrix{4, 4, Int64, 16} with indices SOneTo(4)×SOneTo(4):
 1  4  7  0
 2  5  8  0
 3  6  9  0
 0  0  0  1


3 Likes