Tricks for Swapping Vectors and Matrices with Indexing in Julia
Code
In Julia we present a concise way to change the data type between a vector $\mathbf{x} \in \mathbb{R}^{n}$ and a matrix $A \in \mathbb{R}^{n \times 1}$ that look identical at first glance1. This can serve as an excellent substitute for the vec function (which produces vectors) and the Matrix function (which produces matrices).
julia> x = rand(3)
3-element Vector{Float64}:
0.7442995832650368
0.8715261955707428
0.3513679030410609
julia> A = rand(3, 1)
3×1 Matrix{Float64}:
0.20615245161740703
0.19079463624599347
0.6776521393838526
For example, suppose we have $\mathbf{x} \in \mathbb{R}^{3}$ and $A \in \mathbb{R}^{3 \times 1}$ as above. No lengthy explanation is needed — the example speaks for itself.
From vector to matrix x[:,:]
julia> x[:,:]
3×1 Matrix{Float64}:
0.7442995832650368
0.8715261955707428
0.3513679030410609
From matrix to vector A[:]
julia> A[:]
3-element Vector{Float64}:
0.20615245161740703
0.19079463624599347
0.6776521393838526
