logo

How to Convert between 2D Arrays and Matrices in Julia 📂Julia

How to Convert between 2D Arrays and Matrices in Julia

Overview

Introducing tips for switching between 2D arrays and matrices in Julia, which may be the simplest, fastest, and most beautiful way to do it, especially in environments of Julia 1.7 or lower1.

Code

There are countless ways to switch between matrices and 2D arrays, not just the method introduced here. Since the goal itself is not difficult whether you code haphazardly or not, it’s better to consider not only the goal but also how Julia’s unique syntax was used when reading this carefully.

From matrices to 2D arrays

julia> M = rand(0:9, 3, 10)
3×10 Matrix{Int64}:
 2  4  0  1  8  0  9  2  5  7
 5  2  1  5  4  3  7  2  7  3
 7  8  1  9  0  3  2  4  1  3

Let’s convert the matrix above to a 2D array.

julia> [eachrow(M)...]
3-element Vector{SubArray{Int64, 1, Matrix{Int64}, Tuple{Int64, Base.Slice{Base.OneTo{Int64}}}, true}}:
 [2, 4, 0, 1, 8, 0, 9, 2, 5, 7]
 [5, 2, 1, 5, 4, 3, 7, 2, 7, 3]
 [7, 8, 1, 9, 0, 3, 2, 4, 1, 3]

julia> [eachcol(M)...]
10-element Vector{SubArray{Int64, 1, Matrix{Int64}, Tuple{Base.Slice{Base.OneTo{Int64}}, Int64}, true}}:
 [2, 5, 7]
 [4, 2, 8]
 [0, 1, 1]
 [1, 5, 9]
 [8, 4, 0]
 [0, 3, 3]
 [9, 7, 2]
 [2, 2, 4]
 [5, 7, 1]
 [7, 3, 3]

eachrow() and eachcol() return generators that extract each row and column of the matrix2, and through the splat operator3, handling them as variable arrays and putting them inside square brackets [] naturally turns them into an array.

From 2D arrays to matrices

julia> A = [rand(0:9,3) for _ in 1:10]
10-element Vector{Vector{Int64}}:
 [5, 4, 9]
 [9, 7, 6]
 [9, 9, 6]
 [5, 9, 0]
 [0, 2, 8]
 [3, 9, 5]
 [1, 6, 0]
 [5, 7, 7]
 [1, 3, 5]
 [5, 4, 1]

Let’s covert the above 2D array into a matrix.

julia> hcat(A...)
3×10 Matrix{Int64}:
 5  9  9  5  0  3  1  5  1  5
 4  7  9  9  2  9  6  7  3  4
 9  6  6  0  8  5  0  7  5  1

julia> hcat(A...)'
10×3 adjoint(::Matrix{Int64}) with eltype Int64:
 5  4  9
 9  7  6
 9  9  6
 5  9  0
 0  2  8
 3  9  5
 1  6  0
 5  7  7
 1  3  5
 5  4  1

julia> vcat(A...)
30-element Vector{Int64}:
 5
 4
 9
 9
 7
 6
 9
 9
 ⋮
 7
 1
 3
 5
 5
 4
 1

You can use the hcat() function for merging arrays4. Fundamentally, hcat() and vcat() are fold functions as well as variadic functions, so the one-dimensional arrays, which are elements of the 2D array, have to be passed directly as arguments through the splat operator.

Complete Code

# matrix to 2d array

M = rand(0:9, 3, 10)

[eachrow(M)...]
[eachcol(M)...]

# 2d array to matrix

A = [rand(0:9,3) for _ in 1:10]

hcat(A...)
hcat(A...)'
vcat(A...)

Environment

  • OS: Windows
  • julia: v1.7.0