Julia Arrays

An array is a collection of elements of the same data type arranged in a certain order; it can be a one-dimensional array or a multi-dimensional array.

Julia supports array data structures, which can store an ordered collection whose size is not fixed and whose elements can be of the same or different types.

Julia arrays are mutable typed collections used for lists, vectors, tables, and matrices.

The index keys of Julia arrays can be represented by integers, and the size of an array is not fixed.

Julia provides many functions to help us operate on arrays, such as adding elements to arrays, merging arrays, etc.

Julia arrays use square brackets[...]to specify, and multiple elements use commas,to separate them.

The syntax for creating a one-dimensional array (i.e., a vector) is:

[A, B, C, ...]

Creating One-dimensional Arrays

The following example creates a simple one-dimensional array:

Example

julia> arr = [1,2,3]
3-element Vector{Int64}:
 1
 2
 3

In the above example, we created a one-dimensional array containing 3 elements, each element is a 64-bit integer, and this one-dimensional array is bound to the variablearr.

The types of array elements can also be different:

Example

julia> arr =[1, "EXAMPLE", 2.5, pi]
4-element Vector{Any}:
 1
  "EXAMPLE"
 2.5
 π = 3.1415926535897...

In the above example, we created a one-dimensional array containing 4 elements of different types.piis a constantπ, each element is a 64-bit integer, and this one-dimensional array is bound to the variablearr.

Of course, you can also force the type:

Example

julia> arr = Int64[1,2,3]
3-element Vector{Int64}:
 1
 2
 3
julia> arr2 = String["Taobao","EXAMPLE","GOOGLE"]
3-element Vector{String}:
 "Taobao"
 "EXAMPLE"
 "GOOGLE"

The array in the above examplearris restricted to only integers,arr2is restricted to only strings.

We can also create an empty array:

Example

julia> arr = Int64[]
Int64[]

julia> arr2 = String[]
String[]

The created array can be accessed directly using index values. The first value has index 1 (not 0), the second has index 2, and so on. The last one can useendto represent:

Example

julia> arr = Int64[1,2,3]
3-element Vector{Int64}:
 1
 2
 3

julia> arr[2]
2
julia> arr2 = String["Taobao","EXAMPLE","GOOGLE"]
3-element Vector{String}:
 "Taobao"
 "EXAMPLE"
 "GOOGLE"

julia> arr2[1]
"Taobao"

julia> arr2[end]
"GOOGLE"

Specifying Array Types and Dimensions

We can also use the following syntax to specify the type and dimensions of an array:

Array{type}(undef, dims...)

undefindicates the array is uninitialized.

dims...can be a single or multiple tuple of dimensions, or a set of values when dimensions are passed as variable arguments.

dims...The number represents the number of elements; multiple dimensions use commas,to separate them.

Example

julia> array = Array{Int64}(undef, 3)    # represents a one-dimensional array with 3 elements
3-element Vector{Int64}:
 4834342704
 4377305096
          0

julia> array = Array{Int64}(undef, 3, 3, 3)    # represents a 3-dimensional array, with 3 elements in each dimension
3×3×3 Array{Int64, 3}:
[:, :, 1] =
 4562265712  0  0
          1  0  0
          0  0  0

[:, :, 2] =
 0  0  0
 0  0  0
 0  0  0

[:, :, 3] =
 0  0  0
 0  0  0
 0  0  0

In the above example, we put the type of the array in curly braces{}, undef is used to set the array as uninitialized to any known value; this is why we get random numbers in the output.


Creating Two-dimensional Arrays and Matrices

We can omit the commas between array elements,or use two colons;;, in this way we can create a two-dimensional array, as in the following example:

Example

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

Note:The output in the first line1×4 Matrix{Int64}:, 1x4 represents a matrix with one row and four columns.

Although it has only one row, it is still a two-dimensional array, because Julia only recognizes column vectors, not so-called row vectors.

To add another row, just add a semicolon;, see the following example:

Example

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

You can also use colons:and spaces to achieve this, see the following example:

Example

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

Note:The output in the first line2×2 Matrix{Int64}:, 2×2 represents a matrix with two rows and two columns.

We can also embed one-dimensional arrays of the same length in square brackets[]and separate them with spaces to create a two-dimensional array:

Example

julia> [[1,2] [3,4] [5,6]]
2×3 Matrix{Int64}:
 1  3  5
 2  4  6

2x3represents a two-row, three-column array.

Below we flexibly use semicolons;and spaces to create a two-dimensional array with two rows and three columns, and one with three rows and two columns:

Example

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

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

Using Range Functions to Create Arrays

Ellipsis ...

You can use the ellipsis...to create an array, as in the following example:

Example

julia> [0:10...]
11-element Vector{Int64}:
  0
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10

collect() Function

The syntax of the collect() function is as follows:

collect(start:step:stop)

start is the starting value, step is the step size, and stop is the ending value.

This function returns an array.

In the following example, the value is 1, the step is 2, and the ending value is 13:

Example

julia> collect(1:2:13)
7-element Vector{Int64}:
  1
  3
  5
  7
  9
 11
 13

The collect() function can also specify a type, with the following syntax:

collect(element_type, start:step:stop)

The following example creates a floating-point array:

Example

julia> collect(Float64, 1:2:5)
3-element Vector{Float64}:
 1.0
 3.0
 5.0

range() Function

The range() function can generate an interval range and specify a step size, which is convenient for the collect() function to call.

The syntax of the range() function is as follows:

range(start, stop, length) range(start, stop; length, step) range(start; length, stop, step) range(;start, length, stop, step)

start is the starting value, step is the step size, stop is the ending value, and length is the length.

Example

julia> range(1, length=100)
1:100

julia> range(1, stop=100)
1:100

julia> range(1, step=5, length=100)
1:5:496

julia> range(1, step=5, stop=100)
1:5:96

julia> range(1, 10, length=101)
1.0:0.09:10.0

julia> range(1, 100, step=5)
1:5:96

julia> range(stop=10, length=5)
6:10

julia> range(stop=10, step=1, length=5)
6:1:10

julia> range(start=1, step=1, stop=10)
1:1:10

If length is not specified, andstop - startis not an integer multiple of step, then a range that ends before stop will be generated.

julia> range(1, 3.5, step=2)
1.0:2.0:3.0

Creating arrays with range() and collect():

Example

julia> collect(range(1,stop=10))
10-element Vector{Int64}:
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
julia> collect(range(1, length=15, stop=150))
15-element Vector{Float64}:
   1.0
  11.642857142857142
  22.285714285714285
  32.92857142857143
  43.57142857142857
  54.214285714285715
  64.85714285714286
  75.5
  86.14285714285714
  96.78571428571429
 107.42857142857143
 118.07142857142857
 128.71428571428572
 139.35714285714286
 150.0

Creating Arrays with Comprehensions and Generators

Another useful way to create arrays is by using comprehensions.

The syntax of array comprehensions is as follows:

A = [ F(x,y,...) for x=rx, y=ry, ... ]

F(x,y,...) is evaluated for each value of the variables x, y, etc. in the given lists. The values can be specified as any iterable object, but usually are ranges like 1:n or 2:(n-1), or explicit array values like [1.2, 3.4, 5.7]. The result is an N-dimensional dense array whose dimensions are obtained by concatenating the dimensions of the variable ranges rx, ry, etc., and each evaluation of F(x,y,...) returns a scalar.

Example

julia> [n^2 for n in 1:10]
10-element Vector{Int64}:
   1
   4
   9
  16
  25
  36
  49
  64
  81
 100

Creating a two-dimensional array:

Example

julia> [n*m for n in 1:10, m in 1:10]
10×10 Matrix{Int64}:
  1   2   3   4   5   6   7   8   9   10
  2   4   6   8  10  12  14  16  18   20
  3   6   9  12  15  18  21  24  27   30
  4   8  12  16  20  24  28  32  36   40
  5  10  15  20  25  30  35  40  45   50
  6  12  18  24  30  36  42  48  54   60
  7  14  21  28  35  42  49  56  63   70
  8  16  24  32  40  48  56  64  72   80
  9  18  27  36  45  54  63  72  81   90
 10  20  30  40  50  60  70  80  90  100

Comprehensions can also be written without square brackets, producing an object called a generator.

The following example creates an array:

Example

julia> collect(n^2 for n in 1:5)
5-element Vector{Int64}:
  1
  4
  9
 16
 25

The following expression sums a sequence without allocating memory:

Example

julia> sum(1/n^2 for n=1:1000)
1.6439345666815615

Julia Array Basic Functions

Function Description
eltype(A) Athe type of elements in
length(A) Athe number of elements in
ndims(A) Athe dimension of
size(A) a tuple containingAa tuple with the number of elements in each dimension
size(A,n) ANo.nthe number of elements in dimension
axes(A) a tuple containingAa tuple of valid indices
axes(A,n) No.nthe range of valid indices for dimension
eachindex(A) an efficient iterator for accessingAevery position in
stride(A,k) on thekstride on dimension (distance in linear index between adjacent elements)
strides(A) a tuple containing the stride on each dimension

Julia Construction and Initialization

Julia provides many functions for constructing and initializing arrays. In the following functions, the argument dims ... can be a tuple to represent the dimensions, or a variable number of integer values as dimensions. The first argument of most functions represents the element type T of the array. If the type T is omitted, it defaults to Float64.

Function Description
Array{T}(undef, dims...) A dense array that is uninitializedArray
zeros(T, dims...) An all-zeroArray
ones(T, dims...) An array with all elements equal to 1Array
trues(dims...) An array whose every element istrueofBitArray
falses(dims...) An array whose every element isfalseofBitArray
reshape(A, dims...) An array containing the sameAarray with the same data but different dimensions
copy(A) copyA
deepcopy(A) deep copy, i.e., copyingA, and recursively copying its elements
similar(A, T, dims...) An array with the sameAan uninitialized array having the same type (here refers to dense, sparse, etc.) but with the specified element type and dimensions. The second and third parameters are both optional; if omitted, they default to the element type andAthe dimensions of.
reinterpret(T, A) andAAn array having the same binary data, but the element type isT
rand(T, dims...) A randomArray, the element values are [ 0 , 1 ) [0, 1) uniformly distributed in the half-open interval and obeying first-order independent and identical distribution[1]
randn(T, dims...) A randomArray, elements are standard normal distribution, independent and identically distributed
Matrix{T}(I, m, n) mlinenidentity matrix with columns (need to first executeusing LinearAlgebrain order to useI)
range(start, stop=stop, length=n) fromstarttostopwithnrange of linearly spaced elements
fill!(A, x) With the valuexfill the arrayA
fill(x, dims...) An array filled withxfilledArray

zeros()Create an array instance, element initial values are all 0:

Example

julia> zeros(Int8, 2, 3)
2×3 Matrix{Int8}:
 0  0  0
 0  0  0

julia> zeros(Int8, (2, 3))
2×3 Matrix{Int8}:
 0  0  0
 0  0  0

julia> zeros((2, 3))
2×3 Matrix{Float64}:
 0.0  0.0  0.0
 0.0  0.0  0.0
Other extensions