Resizing and Concatenating Arrays

by Martin D. Maas, Ph.D

Get started handling multidimensional arrays in Julia with this simple guide.

Arrays in Julia are, by default, Dynamic (i.e. growable, resizable) unless defined otherwise. We could change this default behavior by resorting to the StaticArrays.jl package, which can enhance performance for certain type of operations.

But let’s go about how to use the default dynamic arrays in Julia.

Resizing 1D Arrays with Push and Pop

One-dimensional Arrays can be resized with functions such as push! and pop!. In our example below we are using numerical arrays, but these functions can be also applied to non-numerical arrays.

A = Float64[]       # Equivalent to A=Array{Float64}(undef,0)
push!(A, 4)         # Adds the number 4 at the end of the array
push!(A, 3)         # Adds the number 3 at the end of the array
v = pop!(A)         # Returns 3 and removes it from A

There are also functions such as pushfirst!, and popfirst! which work on the beginning of the array as opposed to the end. Additionally, the function splice!(A,i) and deleteat!(A,i) will incorporates (resp. delete) an element at a given position i.

Multi-Dimensional Array Concatenation

A common operation is to concatenate arrays, for example, to add rows to an existing matrix. In Julia, there are a few ways to do this.

Using hcat, vcat, and cat

For example, we can resort to hcat, vcat, and cat functions, to concatenate in the horizontal, vertical, or along any given dimension.

For example,

A = [4 5 6] 
B = [6 7 8] 

M1 = vcat(A, B)
2×3 Matrix{Int64}:
 4  5  6
 6  7  8

M2 = hcat(A, B)
1×6 Matrix{Int64}:
 4  5  6  6  7  8

The cat function, in turn, can be used to acomplish the same results as above. Importantly, cat will also work for n-dimensional arrays, as we can concatenate along any dimension. For example.

M1 = cat(A, B, dims=1)
M2 = cat(A, B, dims=2)
M3 = cat(A, B, dims=3)

Concatenating Matrices

For 2D matrices, we can also resort to the same syntax that we used to input a matrix, using brackets and spaces and semicolons as alternatives to hcat and vcat, respectively.

For example,

M1 = [A; B]
2×3 Matrix{Int64}:
 4  5  6
 6  7  8

M2 = [A B]
1×6 Matrix{Int64}:
 4  5  6  6  7  8


We have covered the basics of Array manipulation, using the Julia Base syntax.

There is, of course, more array functionality in several packages, such as LinearAlgebra.jl, StaticArrays.jl, SparseArrays.jl, which will be the subject of future posts. Stay tuned!