YouTip LogoYouTip

Julia Array

Arrays are collections of elements of the same data type arranged in a specific order. They can be one-dimensional or multi-dimensional. Julia supports array data structures, which can store ordered collections with variable sizes and types that may be the same or different. Julia arrays are mutable collections used for lists, vectors, tables, and matrices. Array indices in Julia can be represented by integers, and the size of an array is not fixed. Julia provides many functions to help us manipulate arrays, such as adding elements and merging arrays. Julia arrays are specified using square brackets [...], with multiple elements separated by commas ,. 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 being a 64-bit integer. This one-dimensional array is bound to the variable `arr`. Array elements can also have different types: ## Example julia> arr =[1, "", 2.5, pi] 4-element Vector{Any}: 1 "" 2.5 Ο€ = 3.1415926535897... In this example, we created a one-dimensional array containing 4 elements of different types. **pi** is the constant **Ο€**, and each element is a 64-bit integer. This one-dimensional array is bound to the variable `arr`. Of course, you can also explicitly specify the type: ## Example julia> arr = Int64[1,2,3] 3-element Vector{Int64}: 1 2 3 julia> arr2 = String["Taobao","","GOOGLE"] 3-element Vector{String}: "Taobao" "" "GOOGLE" In the above examples, array **arr** only allows integers, while **arr2** only allows strings. We can also create an empty array: ## Example julia> arr = Int64[] Int64[] julia> arr2 = String[] String[] Created arrays can directly use index values to access their elements. The first element has an index of 1 (not 0), the second element has an index of 2, and so on. The last element can be accessed using `end`: ## Example julia> arr = Int64[1,2,3] 3-element Vector{Int64}: 1 2 3 julia> arr 2 julia> arr2 = String["Taobao","","GOOGLE"] 3-element Vector{String}: "Taobao" "" "GOOGLE" julia> arr2 "Taobao" julia> arr2 "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...) **undef** indicates that the array has not been initialized. **dims...** can be either a single tuple representing the dimensions, or a set of values when dimensions are passed as variadic arguments. **dims...** numbers represent the number of elements, with multiple dimensions separated by commas ,. ## 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 three-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 examples, the array type is placed within curly braces {}, and `undef` is used to indicate that the array has not been initialized with any known valueβ€”this is why we see random numbers in the output. * * * ## Creating Two-Dimensional Arrays and Matrices We can omit the comma , between array elements or use two colons ;; to create a two-dimensional array, as shown in the following example: ## Example julia> 1Γ—4 Matrix{Int64}: 1 2 3 4 julia>[1;;2;;3;;4] 1Γ—4 Matrix{Int64}: 1 2 3 4 **Note:** The first line shows `1Γ—4 Matrix{Int64}:`, where 1x4 means a matrix with one row and four columns. Although it has only one row, it is still considered a two-dimensional array because Julia recognizes only column vectors and does not recognize so-called row vectors. To add another row, simply add a semicolon ;, as shown in 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 the same result, as shown in the following example: ## Example julia>[1:2 3:4] 2Γ—2 Matrix{Int64}: 1 3 2 4 **Note:** The first line shows `2Γ—2 Matrix{Int64}:`, where 2Γ—2 means a matrix with two rows and two columns. We can also embed multiple one-dimensional arrays of equal length within 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 **2x3** means a matrix with two rows and three columns. Next, by flexibly using semicolons ; and spaces , we can create two-dimensional arrays with two rows and three columns, as well as three rows and two columns: ## Example julia>[[1;2][3;4][5;6]] 2Γ—3 Matrix{Int64}: 1 3 5 2 4 6 julia>[;;] 3Γ—2 Matrix{Int64}: 1 2 3 4 5 6 * * * ## Using Range Functions to Create Arrays ### Ellipsis ... You can use ellipses ... to create an array, as shown 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 for the `collect()` function is as follows: collect(start:step:stop) where `start` is the starting value, `step` is the step size, and `stop` is the ending value. This function returns an array. The following example uses a start value of 1, a step size of 2, and an ending value of 13: ## Example julia>collect(1:2:13) 7-element Vector{Int64}: 1 3 5 7 9 11 13 The `collect()` function can also specify the 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 a range of values and specify the step size, making it convenient for the `collect()` function to call. The syntax for 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) where `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 no length `length` is specified and `stop - start` is not an integer multiple of `step`, then a range will be generated that ends before `stop`. julia> range(1, 3.5, step=2)1.0:2.0:3.0 Using `range()` and `collect()` to create arrays: ## 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 ### Using Comprehensions and Generators to Create Arrays Another useful method for creating arrays is to use comprehensions. The syntax for array comprehensions is as follows: A = [ F(x,y,...) for x=rx, y=ry, ... ] F(x,y,...) calculates each value of variables x, y, etc., from its given list. Values can be specified as any iterable object, but are usually ranges like 1:n or 2:(n-1), or explicit array values such as [1.2, 3.4, 5.7]. The result is an N-dimensional dense array, with the dimensions of variables rx, ry, etc., concatenated to form its overall dimension, and each calculation 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 You can also write array comprehensions without square brackets, thereby generating objects called generators. 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 ## Basic Functions for Julia Arrays | Function | Description | | --- | --- | | `eltype(A)` | The type of elements in `A` | | `length(A)` | The number of elements in `A` | | `ndims(A)` | The number of dimensions of `A` | | `size(A)` | A tuple containing the number of elements along each dimension of `A` | | `size(A,n)` | The number of elements in the `n`th dimension of `A` | | `axes(A)` | A tuple containing valid indices for `A` | | `axes(A,n)` | The range of valid indices for the `n`th dimension of `A` | | `eachindex(A)` | An efficient iterator for accessing every position in `A` | | `stride(A,k)` | The interval (stride) on the `k`th dimension (the linear index distance between adjacent elements) | | `strides(A)` | A tuple containing the intervals (strides) on each dimension | ## Julia Construction and Initialization Julia provides many functions for constructing and initializing arrays. In most of these functions, the parameter `dims ...` can be a tuple representing dimensions, or a variable-length sequence of integers serving 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` without initialization | | `zeros(T, dims...)` | A completely zero-filled `Array` | | `ones(T, dims...)` | An `Array` with all elements equal to 1 | | `trues(dims...)` | A `BitArray` with all elements equal to `true` | | `falses(dims...)` | A `BitArray` with all elements equal to `false` | | `reshape(A, dims...)` | An array with the same data as `A` but different dimensions | | `copy(A)` | A copy of `A` | | `deepcopy(A)` | A deep copy, i.e., a copy of `A` that recursively copies its elements | | `similar(A, T, dims...)` | An uninitialized array with the same type as `A` (e.g., dense, sparse, etc.), but with specified element type and dimensions. The second and third parameters are optional; if omitted, they default to the element type and dimensions of `A`. | | `reinterpret(T, A)` | An array with the same binary data as `A`, but with element type `T` | | `rand(T, dims...)` | A random `Array` whose elements follow a uniform distribution in the half-open interval [0, 1) and are independently and identically distributed [](#) | | `randn(T, dims...)` | A random `Array` whose elements follow a standard normal distribution and are independently and identically distributed | | `Matrix{T}(I, m, n)` | A unit matrix with `m` rows and `n` columns (requires `using LinearAlgebra` to use `I`) | | `range(start, stop=stop, length=n)` | A range with `n` linearly spaced elements from `start` to `stop` | | `fill!(A, x)` | Fill array `A` with value `x` | | `fill(x, dims...)` | An `Array` filled with value `x` | **zeros()** creates an array instance where all initial element values are 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
← Julia Data TypeJulia Basic Syntax β†’