logo

How to Use Circular Arrangements in Julia 📂Julia

How to Use Circular Arrangements in Julia

Overview

Though Julia does not natively support Circular Arrays, it essentially allows for such functionality by providing the circshift() function, which pushes or pulls elements circularly1. It’s not particularly difficult to write this function yourself, but knowing it obviates the need. This function can be used almost exactly like the circshift() in MATLAB.

Code

This function has been introduced in the post about how to translate arrays in parallel as well.

Basic Usage

julia> circshift(1:4, 1)
4-element Vector{Int64}:
 4
 1
 2
 3

julia> circshift(1:4, -1)
4-element Vector{Int64}:
 2
 3
 4
 1

circshift() basically takes an integer as the second argument to push or pull elements. In the example above, positive integers cause a backward (downward) shift, while negative integers cause a forward (upward) shift.

Multidimensional Arrays

julia> ca = reshape(1:20, 5, :)
5×4 reshape(::UnitRange{Int64}, 5, 4) with eltype Int64:
 1   6  11  16
 2   7  12  17
 3   8  13  18
 4   9  14  19
 5  10  15  20

Given a multidimensional array like the one above, you specify a tuple of the same dimension to determine how much to push or pull each dimension.

julia> circshift(ca, (0,1))
5×4 Matrix{Int64}:
 16  1   6  11
 17  2   7  12
 18  3   8  13
 19  4   9  14
 20  5  10  15

julia> circshift(ca, (-1,0))
5×4 Matrix{Int64}:
 2   7  12  17
 3   8  13  18
 4   9  14  19
 5  10  15  20
 1   6  11  16

julia> circshift(ca, (-1,1))
5×4 Matrix{Int64}:
 17  2   7  12
 18  3   8  13
 19  4   9  14
 20  5  10  15
 16  1   6  11

Complete Code

circshift(1:4, 1)
circshift(1:4, -1)

ca = reshape(1:20, 5, :)
circshift(ca, (0,1))
circshift(ca, (-1,0))
circshift(ca, (-1,1))

Environment

  • OS: Windows
  • julia: v1.8.5