How can I efficiently resize a matrix in julia?

Viewed 155

What is the efficient way to resize a matrix along the first dimension, i.e. add rows?

1 Answers

It is not possible for standard Matrix type. You can only resize Vector by e.g. doing append! or push!.

You can vertically concatenate two matrices, but this allocates a new matrix:

julia> x = [1 2; 3 4]
2×2 Matrix{Int64}:
 1  2
 3  4

julia> y = [5 6; 7 8]
2×2 Matrix{Int64}:
 5  6
 7  8

julia> [x; y]
4×2 Matrix{Int64}:
 1  2
 3  4
 5  6
 7  8

The reason why adding a new row a matrix in-place is not supported is that it cannot be done efficiently because of the memory layout of a matrix (essentially the cost of such operation would be similar to vertical concatenation).

You would need another data structure to be able to do such resizing in place. For example DataFrame from DataFrames.jl supports this (but note that quite likely vertical concatenation I have described above is best for your use case):

julia> using DataFrames

julia> df = DataFrame(a=[1,2], b=[11,12])
2×2 DataFrame
 Row │ a      b
     │ Int64  Int64
─────┼──────────────
   1 │     1     11
   2 │     2     12

julia> push!(df, [3, 13])
3×2 DataFrame
 Row │ a      b
     │ Int64  Int64
─────┼──────────────
   1 │     1     11
   2 │     2     12
   3 │     3     13

The reason why it is possible for DataFrame efficiently is that internally it is a vector of vectors so you can push! data to each vector representing a column.

Related