Initialise array without specific types

If you know that your matrix will have a type which matches some function input, then you can use that:

julia> function build_matrix(x)
         out = Matrix{typeof(x)}(undef, 2, 2)
         for i in 1:2
           out[:, i] .= x
         end
         out
       end
build_matrix (generic function with 1 method)

julia> build_matrix(1)
2×2 Matrix{Int64}:
 1  1
 1  1

julia> build_matrix(1.0)
2×2 Matrix{Float64}:
 1.0  1.0
 1.0  1.0

or, equivalently:

julia> function build_matrix(x::T) where {T}
         out = Matrix{T}(undef, 2, 2)
         ...

Alternatively, if you have easy access to the individual rows, you can do:

cext = permutedims(reduce(hcat, rows))

where rows is a vector of vectors.

By the way, you will get better performance if you transpose your data so that you are frequently accessing individual columns of the matrix rather than rows. This is because Julia arrays are column-major, just like fortran and matlab but unlike C and numpy.

3 Likes