Arrays

Constructors and Types

Core.AbstractArray — Type

  1. AbstractArray{T,N}

Supertype for N-dimensional arrays (or array-like types) with elements of type T. Array and other types are subtypes of this. See the manual section on the AbstractArray interface.

See also: AbstractVector, AbstractMatrix, eltype, ndims.

source

Base.AbstractVector — Type

  1. AbstractVector{T}

Supertype for one-dimensional arrays (or array-like types) with elements of type T. Alias for AbstractArray{T,1}.

source

Base.AbstractMatrix — Type

  1. AbstractMatrix{T}

Supertype for two-dimensional arrays (or array-like types) with elements of type T. Alias for AbstractArray{T,2}.

source

Base.AbstractVecOrMat — Type

  1. AbstractVecOrMat{T}

Union type of AbstractVector{T} and AbstractMatrix{T}.

source

Core.Array — Type

  1. Array{T,N} <: AbstractArray{T,N}

N-dimensional dense array with elements of type T.

source

Core.Array — Method

  1. Array{T}(undef, dims)
  2. Array{T,N}(undef, dims)

Construct an uninitialized N-dimensional Array containing elements of type T. N can either be supplied explicitly, as in Array{T,N}(undef, dims), or be determined by the length or number of dims. dims may be a tuple or a series of integer arguments corresponding to the lengths in each dimension. If the rank N is supplied explicitly, then it must match the length or number of dims. Here undef is the UndefInitializer.

Examples

  1. julia> A = Array{Float64, 2}(undef, 2, 3) # N given explicitly
  2. 2×3 Matrix{Float64}:
  3. 6.90198e-310 6.90198e-310 6.90198e-310
  4. 6.90198e-310 6.90198e-310 0.0
  5. julia> B = Array{Float64}(undef, 4) # N determined by the input
  6. 4-element Vector{Float64}:
  7. 2.360075077e-314
  8. NaN
  9. 2.2671131793e-314
  10. 2.299821756e-314
  11. julia> similar(B, 2, 4, 1) # use typeof(B), and the given size
  12. 2×4×1 Array{Float64, 3}:
  13. [:, :, 1] =
  14. 2.26703e-314 2.26708e-314 0.0 2.80997e-314
  15. 0.0 2.26703e-314 2.26708e-314 0.0

source

Core.Array — Method

  1. Array{T}(nothing, dims)
  2. Array{T,N}(nothing, dims)

Construct an N-dimensional Array containing elements of type T, initialized with nothing entries. Element type T must be able to hold these values, i.e. Nothing <: T.

Examples

  1. julia> Array{Union{Nothing, String}}(nothing, 2)
  2. 2-element Vector{Union{Nothing, String}}:
  3. nothing
  4. nothing
  5. julia> Array{Union{Nothing, Int}}(nothing, 2, 3)
  6. 2×3 Matrix{Union{Nothing, Int64}}:
  7. nothing nothing nothing
  8. nothing nothing nothing

source

Core.Array — Method

  1. Array{T}(missing, dims)
  2. Array{T,N}(missing, dims)

Construct an N-dimensional Array containing elements of type T, initialized with missing entries. Element type T must be able to hold these values, i.e. Missing <: T.

Examples

  1. julia> Array{Union{Missing, String}}(missing, 2)
  2. 2-element Vector{Union{Missing, String}}:
  3. missing
  4. missing
  5. julia> Array{Union{Missing, Int}}(missing, 2, 3)
  6. 2×3 Matrix{Union{Missing, Int64}}:
  7. missing missing missing
  8. missing missing missing

source

Core.UndefInitializer — Type

  1. UndefInitializer

Singleton type used in array initialization, indicating the array-constructor-caller would like an uninitialized array. See also undef, an alias for UndefInitializer().

Examples

  1. julia> Array{Float64, 1}(UndefInitializer(), 3)
  2. 3-element Array{Float64, 1}:
  3. 2.2752528595e-314
  4. 2.202942107e-314
  5. 2.275252907e-314

source

Core.undef — Constant

  1. undef

Alias for UndefInitializer(), which constructs an instance of the singleton type UndefInitializer, used in array initialization to indicate the array-constructor-caller would like an uninitialized array.

See also: missing, similar.

Examples

  1. julia> Array{Float64, 1}(undef, 3)
  2. 3-element Vector{Float64}:
  3. 2.2752528595e-314
  4. 2.202942107e-314
  5. 2.275252907e-314

source

Base.Vector — Type

  1. Vector{T} <: AbstractVector{T}

One-dimensional dense array with elements of type T, often used to represent a mathematical vector. Alias for Array{T,1}.

See also empty, similar and zero for creating vectors.

source

Base.Vector — Method

  1. Vector{T}(undef, n)

Construct an uninitialized Vector{T} of length n.

Examples

  1. julia> Vector{Float64}(undef, 3)
  2. 3-element Array{Float64, 1}:
  3. 6.90966e-310
  4. 6.90966e-310
  5. 6.90966e-310

source

Base.Vector — Method

  1. Vector{T}(nothing, m)

Construct a Vector{T} of length m, initialized with nothing entries. Element type T must be able to hold these values, i.e. Nothing <: T.

Examples

  1. julia> Vector{Union{Nothing, String}}(nothing, 2)
  2. 2-element Vector{Union{Nothing, String}}:
  3. nothing
  4. nothing

source

Base.Vector — Method

  1. Vector{T}(missing, m)

Construct a Vector{T} of length m, initialized with missing entries. Element type T must be able to hold these values, i.e. Missing <: T.

Examples

  1. julia> Vector{Union{Missing, String}}(missing, 2)
  2. 2-element Vector{Union{Missing, String}}:
  3. missing
  4. missing

source

Base.Matrix — Type

  1. Matrix{T} <: AbstractMatrix{T}

Two-dimensional dense array with elements of type T, often used to represent a mathematical matrix. Alias for Array{T,2}.

See also fill, zeros, undef and similar for creating matrices.

source

Base.Matrix — Method

  1. Matrix{T}(undef, m, n)

Construct an uninitialized Matrix{T} of size m×n.

Examples

  1. julia> Matrix{Float64}(undef, 2, 3)
  2. 2×3 Array{Float64, 2}:
  3. 2.36365e-314 2.28473e-314 5.0e-324
  4. 2.26704e-314 2.26711e-314 NaN
  5. julia> similar(ans, Int32, 2, 2)
  6. 2×2 Matrix{Int32}:
  7. 490537216 1277177453
  8. 1 1936748399

source

Base.Matrix — Method

  1. Matrix{T}(nothing, m, n)

Construct a Matrix{T} of size m×n, initialized with nothing entries. Element type T must be able to hold these values, i.e. Nothing <: T.

Examples

  1. julia> Matrix{Union{Nothing, String}}(nothing, 2, 3)
  2. 2×3 Matrix{Union{Nothing, String}}:
  3. nothing nothing nothing
  4. nothing nothing nothing

source

Base.Matrix — Method

  1. Matrix{T}(missing, m, n)

Construct a Matrix{T} of size m×n, initialized with missing entries. Element type T must be able to hold these values, i.e. Missing <: T.

Examples

  1. julia> Matrix{Union{Missing, String}}(missing, 2, 3)
  2. 2×3 Matrix{Union{Missing, String}}:
  3. missing missing missing
  4. missing missing missing

source

Base.VecOrMat — Type

  1. VecOrMat{T}

Union type of Vector{T} and Matrix{T} which allows functions to accept either a Matrix or a Vector.

Examples

  1. julia> Vector{Float64} <: VecOrMat{Float64}
  2. true
  3. julia> Matrix{Float64} <: VecOrMat{Float64}
  4. true
  5. julia> Array{Float64, 3} <: VecOrMat{Float64}
  6. false

source

Core.DenseArray — Type

  1. DenseArray{T, N} <: AbstractArray{T,N}

N-dimensional dense array with elements of type T. The elements of a dense array are stored contiguously in memory.

source

Base.DenseVector — Type

  1. DenseVector{T}

One-dimensional DenseArray with elements of type T. Alias for DenseArray{T,1}.

source

Base.DenseMatrix — Type

  1. DenseMatrix{T}

Two-dimensional DenseArray with elements of type T. Alias for DenseArray{T,2}.

source

Base.DenseVecOrMat — Type

  1. DenseVecOrMat{T}

Union type of DenseVector{T} and DenseMatrix{T}.

source

Base.StridedArray — Type

  1. StridedArray{T, N}

A hard-coded Union of common array types that follow the strided array interface, with elements of type T and N dimensions.

If A is a StridedArray, then its elements are stored in memory with offsets, which may vary between dimensions but are constant within a dimension. For example, A could have stride 2 in dimension 1, and stride 3 in dimension 2. Incrementing A along dimension d jumps in memory by [strides(A, d)] slots. Strided arrays are particularly important and useful because they can sometimes be passed directly as pointers to foreign language libraries like BLAS.

source

Base.StridedVector — Type

  1. StridedVector{T}

One dimensional StridedArray with elements of type T.

source

Base.StridedMatrix — Type

  1. StridedMatrix{T}

Two dimensional StridedArray with elements of type T.

source

Base.StridedVecOrMat — Type

  1. StridedVecOrMat{T}

Union type of StridedVector and StridedMatrix with elements of type T.

source

Base.Slices — Type

  1. Slices{P,SM,AX,S,N} <: AbstractSlices{S,N}

An AbstractArray of slices into a parent array over specified dimension(s), returning views that select all the data from the other dimension(s).

These should typically be constructed by eachslice, eachcol or eachrow.

parent(s::Slices) will return the parent array.

source

Base.RowSlices — Type

  1. RowSlices{M,AX,S}

A special case of Slices that is a vector of row slices of a matrix, as constructed by eachrow.

parent can be used to get the underlying matrix.

source

Base.ColumnSlices — Type

  1. ColumnSlices{M,AX,S}

A special case of Slices that is a vector of column slices of a matrix, as constructed by eachcol.

parent can be used to get the underlying matrix.

source

Base.getindex — Method

  1. getindex(type[, elements...])

Construct a 1-d array of the specified type. This is usually called with the syntax Type[]. Element values can be specified using Type[a,b,c,...].

Examples

  1. julia> Int8[1, 2, 3]
  2. 3-element Vector{Int8}:
  3. 1
  4. 2
  5. 3
  6. julia> getindex(Int8, 1, 2, 3)
  7. 3-element Vector{Int8}:
  8. 1
  9. 2
  10. 3

source

Base.zeros — Function

  1. zeros([T=Float64,] dims::Tuple)
  2. zeros([T=Float64,] dims...)

Create an Array, with element type T, of all zeros with size specified by dims. See also fill, ones, zero.

Examples

  1. julia> zeros(1)
  2. 1-element Vector{Float64}:
  3. 0.0
  4. julia> zeros(Int8, 2, 3)
  5. 2×3 Matrix{Int8}:
  6. 0 0 0
  7. 0 0 0

source

Base.ones — Function

  1. ones([T=Float64,] dims::Tuple)
  2. ones([T=Float64,] dims...)

Create an Array, with element type T, of all ones with size specified by dims. See also fill, zeros.

Examples

  1. julia> ones(1,2)
  2. 1×2 Matrix{Float64}:
  3. 1.0 1.0
  4. julia> ones(ComplexF64, 2, 3)
  5. 2×3 Matrix{ComplexF64}:
  6. 1.0+0.0im 1.0+0.0im 1.0+0.0im
  7. 1.0+0.0im 1.0+0.0im 1.0+0.0im

source

Base.BitArray — Type

  1. BitArray{N} <: AbstractArray{Bool, N}

Space-efficient N-dimensional boolean array, using just one bit for each boolean value.

BitArrays pack up to 64 values into every 8 bytes, resulting in an 8x space efficiency over Array{Bool, N} and allowing some operations to work on 64 values at once.

By default, Julia returns BitArrays from broadcasting operations that generate boolean elements (including dotted-comparisons like .==) as well as from the functions trues and falses.

Note

Due to its packed storage format, concurrent access to the elements of a BitArray where at least one of them is a write is not thread-safe.

source

Base.BitArray — Method

  1. BitArray(undef, dims::Integer...)
  2. BitArray{N}(undef, dims::NTuple{N,Int})

Construct an undef BitArray with the given dimensions. Behaves identically to the Array constructor. See undef.

Examples

  1. julia> BitArray(undef, 2, 2)
  2. 2×2 BitMatrix:
  3. 0 0
  4. 0 0
  5. julia> BitArray(undef, (3, 1))
  6. 3×1 BitMatrix:
  7. 0
  8. 0
  9. 0

source

Base.BitArray — Method

  1. BitArray(itr)

Construct a BitArray generated by the given iterable object. The shape is inferred from the itr object.

Examples

  1. julia> BitArray([1 0; 0 1])
  2. 2×2 BitMatrix:
  3. 1 0
  4. 0 1
  5. julia> BitArray(x+y == 3 for x = 1:2, y = 1:3)
  6. 2×3 BitMatrix:
  7. 0 1 0
  8. 1 0 0
  9. julia> BitArray(x+y == 3 for x = 1:2 for y = 1:3)
  10. 6-element BitVector:
  11. 0
  12. 1
  13. 0
  14. 1
  15. 0
  16. 0

source

Base.trues — Function

  1. trues(dims)

Create a BitArray with all values set to true.

Examples

  1. julia> trues(2,3)
  2. 2×3 BitMatrix:
  3. 1 1 1
  4. 1 1 1

source

Base.falses — Function

  1. falses(dims)

Create a BitArray with all values set to false.

Examples

  1. julia> falses(2,3)
  2. 2×3 BitMatrix:
  3. 0 0 0
  4. 0 0 0

source

Base.fill — Function

  1. fill(value, dims::Tuple)
  2. fill(value, dims...)

Create an array of size dims with every location set to value.

For example, fill(1.0, (5,5)) returns a 5×5 array of floats, with 1.0 in every location of the array.

The dimension lengths dims may be specified as either a tuple or a sequence of arguments. An N-length tuple or N arguments following the value specify an N-dimensional array. Thus, a common idiom for creating a zero-dimensional array with its only location set to x is fill(x).

Every location of the returned array is set to (and is thus \=== to) the value that was passed; this means that if the value is itself modified, all elements of the filled array will reflect that modification because they’re still that very value. This is of no concern with fill(1.0, (5,5)) as the value 1.0 is immutable and cannot itself be modified, but can be unexpected with mutable values like — most commonly — arrays. For example, fill([], 3) places the very same empty array in all three locations of the returned vector:

  1. julia> v = fill([], 3)
  2. 3-element Vector{Vector{Any}}:
  3. []
  4. []
  5. []
  6. julia> v[1] === v[2] === v[3]
  7. true
  8. julia> value = v[1]
  9. Any[]
  10. julia> push!(value, 867_5309)
  11. 1-element Vector{Any}:
  12. 8675309
  13. julia> v
  14. 3-element Vector{Vector{Any}}:
  15. [8675309]
  16. [8675309]
  17. [8675309]

To create an array of many independent inner arrays, use a comprehension instead. This creates a new and distinct array on each iteration of the loop:

  1. julia> v2 = [[] for _ in 1:3]
  2. 3-element Vector{Vector{Any}}:
  3. []
  4. []
  5. []
  6. julia> v2[1] === v2[2] === v2[3]
  7. false
  8. julia> push!(v2[1], 8675309)
  9. 1-element Vector{Any}:
  10. 8675309
  11. julia> v2
  12. 3-element Vector{Vector{Any}}:
  13. [8675309]
  14. []
  15. []

See also: fill!, zeros, ones, similar.

Examples

  1. julia> fill(1.0, (2,3))
  2. 2×3 Matrix{Float64}:
  3. 1.0 1.0 1.0
  4. 1.0 1.0 1.0
  5. julia> fill(42)
  6. 0-dimensional Array{Int64, 0}:
  7. 42
  8. julia> A = fill(zeros(2), 2) # sets both elements to the same [0.0, 0.0] vector
  9. 2-element Vector{Vector{Float64}}:
  10. [0.0, 0.0]
  11. [0.0, 0.0]
  12. julia> A[1][1] = 42; # modifies the filled value to be [42.0, 0.0]
  13. julia> A # both A[1] and A[2] are the very same vector
  14. 2-element Vector{Vector{Float64}}:
  15. [42.0, 0.0]
  16. [42.0, 0.0]

source

Base.fill! — Function

  1. fill!(A, x)

Fill array A with the value x. If x is an object reference, all elements will refer to the same object. fill!(A, Foo()) will return A filled with the result of evaluating Foo() once.

Examples

  1. julia> A = zeros(2,3)
  2. 2×3 Matrix{Float64}:
  3. 0.0 0.0 0.0
  4. 0.0 0.0 0.0
  5. julia> fill!(A, 2.)
  6. 2×3 Matrix{Float64}:
  7. 2.0 2.0 2.0
  8. 2.0 2.0 2.0
  9. julia> a = [1, 1, 1]; A = fill!(Vector{Vector{Int}}(undef, 3), a); a[1] = 2; A
  10. 3-element Vector{Vector{Int64}}:
  11. [2, 1, 1]
  12. [2, 1, 1]
  13. [2, 1, 1]
  14. julia> x = 0; f() = (global x += 1; x); fill!(Vector{Int}(undef, 3), f())
  15. 3-element Vector{Int64}:
  16. 1
  17. 1
  18. 1

source

Base.empty — Function

  1. empty(x::Tuple)

Return an empty tuple, ().

source

  1. empty(v::AbstractVector, [eltype])

Create an empty vector similar to v, optionally changing the eltype.

See also: empty!, isempty, isassigned.

Examples

  1. julia> empty([1.0, 2.0, 3.0])
  2. Float64[]
  3. julia> empty([1.0, 2.0, 3.0], String)
  4. String[]

source

  1. empty(a::AbstractDict, [index_type=keytype(a)], [value_type=valtype(a)])

Create an empty AbstractDict container which can accept indices of type index_type and values of type value_type. The second and third arguments are optional and default to the input’s keytype and valtype, respectively. (If only one of the two types is specified, it is assumed to be the value_type, and the index_type we default to keytype(a)).

Custom AbstractDict subtypes may choose which specific dictionary type is best suited to return for the given index and value types, by specializing on the three-argument signature. The default is to return an empty Dict.

source

Base.similar — Function

  1. similar(A::AbstractSparseMatrixCSC{Tv,Ti}, [::Type{TvNew}, ::Type{TiNew}, m::Integer, n::Integer]) where {Tv,Ti}

Create an uninitialized mutable array with the given element type, index type, and size, based upon the given source SparseMatrixCSC. The new sparse matrix maintains the structure of the original sparse matrix, except in the case where dimensions of the output matrix are different from the output.

The output matrix has zeros in the same locations as the input, but unititialized values for the nonzero locations.

  1. similar(array, [element_type=eltype(array)], [dims=size(array)])

Create an uninitialized mutable array with the given element type and size, based upon the given source array. The second and third arguments are both optional, defaulting to the given array’s eltype and size. The dimensions may be specified either as a single tuple argument or as a series of integer arguments.

Custom AbstractArray subtypes may choose which specific array type is best-suited to return for the given element type and dimensionality. If they do not specialize this method, the default is an Array{element_type}(undef, dims...).

For example, similar(1:10, 1, 4) returns an uninitialized Array{Int,2} since ranges are neither mutable nor support 2 dimensions:

  1. julia> similar(1:10, 1, 4)
  2. 1×4 Matrix{Int64}:
  3. 4419743872 4374413872 4419743888 0

Conversely, similar(trues(10,10), 2) returns an uninitialized BitVector with two elements since BitArrays are both mutable and can support 1-dimensional arrays:

  1. julia> similar(trues(10,10), 2)
  2. 2-element BitVector:
  3. 0
  4. 0

Since BitArrays can only store elements of type Bool, however, if you request a different element type it will create a regular Array instead:

  1. julia> similar(falses(10), Float64, 2, 4)
  2. 2×4 Matrix{Float64}:
  3. 2.18425e-314 2.18425e-314 2.18425e-314 2.18425e-314
  4. 2.18425e-314 2.18425e-314 2.18425e-314 2.18425e-314

See also: undef, isassigned.

source

  1. similar(storagetype, axes)

Create an uninitialized mutable array analogous to that specified by storagetype, but with axes specified by the last argument.

Examples:

  1. similar(Array{Int}, axes(A))

creates an array that “acts like” an Array{Int} (and might indeed be backed by one), but which is indexed identically to A. If A has conventional indexing, this will be identical to Array{Int}(undef, size(A)), but if A has unconventional indexing then the indices of the result will match A.

  1. similar(BitArray, (axes(A, 2),))

would create a 1-dimensional logical array whose indices match those of the columns of A.

source

Basic functions

Base.ndims — Function

  1. ndims(A::AbstractArray) -> Integer

Return the number of dimensions of A.

See also: size, axes.

Examples

  1. julia> A = fill(1, (3,4,5));
  2. julia> ndims(A)
  3. 3

source

Base.size — Function

  1. size(A::AbstractArray, [dim])

Return a tuple containing the dimensions of A. Optionally you can specify a dimension to just get the length of that dimension.

Note that size may not be defined for arrays with non-standard indices, in which case axes may be useful. See the manual chapter on arrays with custom indices.

See also: length, ndims, eachindex, sizeof.

Examples

  1. julia> A = fill(1, (2,3,4));
  2. julia> size(A)
  3. (2, 3, 4)
  4. julia> size(A, 2)
  5. 3

source

Base.axes — Method

  1. axes(A)

Return the tuple of valid indices for array A.

See also: size, keys, eachindex.

Examples

  1. julia> A = fill(1, (5,6,7));
  2. julia> axes(A)
  3. (Base.OneTo(5), Base.OneTo(6), Base.OneTo(7))

source

Base.axes — Method

  1. axes(A, d)

Return the valid range of indices for array A along dimension d.

See also size, and the manual chapter on arrays with custom indices.

Examples

  1. julia> A = fill(1, (5,6,7));
  2. julia> axes(A, 2)
  3. Base.OneTo(6)
  4. julia> axes(A, 4) == 1:1 # all dimensions d > ndims(A) have size 1
  5. true

Usage note

Each of the indices has to be an AbstractUnitRange{<:Integer}, but at the same time can be a type that uses custom indices. So, for example, if you need a subset, use generalized indexing constructs like begin/end or firstindex/lastindex:

  1. ix = axes(v, 1)
  2. ix[2:end] # will work for eg Vector, but may fail in general
  3. ix[(begin+1):end] # works for generalized indexes

source

Base.length — Method

  1. length(A::AbstractArray)

Return the number of elements in the array, defaults to prod(size(A)).

Examples

  1. julia> length([1, 2, 3, 4])
  2. 4
  3. julia> length([1 2; 3 4])
  4. 4

source

Base.keys — Method

  1. keys(a::AbstractArray)

Return an efficient array describing all valid indices for a arranged in the shape of a itself.

The keys of 1-dimensional arrays (vectors) are integers, whereas all other N-dimensional arrays use CartesianIndex to describe their locations. Often the special array types LinearIndices and CartesianIndices are used to efficiently represent these arrays of integers and CartesianIndexes, respectively.

Note that the keys of an array might not be the most efficient index type; for maximum performance use eachindex instead.

Examples

  1. julia> keys([4, 5, 6])
  2. 3-element LinearIndices{1, Tuple{Base.OneTo{Int64}}}:
  3. 1
  4. 2
  5. 3
  6. julia> keys([4 5; 6 7])
  7. CartesianIndices((2, 2))

source

Base.eachindex — Function

  1. eachindex(A...)
  2. eachindex(::IndexStyle, A::AbstractArray...)

Create an iterable object for visiting each index of an AbstractArray A in an efficient manner. For array types that have opted into fast linear indexing (like Array), this is simply the range 1:length(A) if they use 1-based indexing. For array types that have not opted into fast linear indexing, a specialized Cartesian range is typically returned to efficiently index into the array with indices specified for every dimension.

In general eachindex accepts arbitrary iterables, including strings and dictionaries, and returns an iterator object supporting arbitrary index types (e.g. unevenly spaced or non-integer indices).

If A is AbstractArray it is possible to explicitly specify the style of the indices that should be returned by eachindex by passing a value having IndexStyle type as its first argument (typically IndexLinear() if linear indices are required or IndexCartesian() if Cartesian range is wanted).

If you supply more than one AbstractArray argument, eachindex will create an iterable object that is fast for all arguments (typically a UnitRange if all inputs have fast linear indexing, a CartesianIndices otherwise). If the arrays have different sizes and/or dimensionalities, a DimensionMismatch exception will be thrown.

See also pairs(A) to iterate over indices and values together, and axes(A, 2) for valid indices along one dimension.

Examples

  1. julia> A = [10 20; 30 40];
  2. julia> for i in eachindex(A) # linear indexing
  3. println("A[", i, "] == ", A[i])
  4. end
  5. A[1] == 10
  6. A[2] == 30
  7. A[3] == 20
  8. A[4] == 40
  9. julia> for i in eachindex(view(A, 1:2, 1:1)) # Cartesian indexing
  10. println(i)
  11. end
  12. CartesianIndex(1, 1)
  13. CartesianIndex(2, 1)

source

Base.IndexStyle — Type

  1. IndexStyle(A)
  2. IndexStyle(typeof(A))

IndexStyle specifies the “native indexing style” for array A. When you define a new AbstractArray type, you can choose to implement either linear indexing (with IndexLinear) or cartesian indexing. If you decide to only implement linear indexing, then you must set this trait for your array type:

  1. Base.IndexStyle(::Type{<:MyArray}) = IndexLinear()

The default is IndexCartesian().

Julia’s internal indexing machinery will automatically (and invisibly) recompute all indexing operations into the preferred style. This allows users to access elements of your array using any indexing style, even when explicit methods have not been provided.

If you define both styles of indexing for your AbstractArray, this trait can be used to select the most performant indexing style. Some methods check this trait on their inputs, and dispatch to different algorithms depending on the most efficient access pattern. In particular, eachindex creates an iterator whose type depends on the setting of this trait.

source

Base.IndexLinear — Type

  1. IndexLinear()

Subtype of IndexStyle used to describe arrays which are optimally indexed by one linear index.

A linear indexing style uses one integer index to describe the position in the array (even if it’s a multidimensional array) and column-major ordering is used to efficiently access the elements. This means that requesting eachindex from an array that is IndexLinear will return a simple one-dimensional range, even if it is multidimensional.

A custom array that reports its IndexStyle as IndexLinear only needs to implement indexing (and indexed assignment) with a single Int index; all other indexing expressions — including multidimensional accesses — will be recomputed to the linear index. For example, if A were a 2×3 custom matrix with linear indexing, and we referenced A[1, 3], this would be recomputed to the equivalent linear index and call A[5] since 2*1 + 3 = 5.

See also IndexCartesian.

source

Base.IndexCartesian — Type

  1. IndexCartesian()

Subtype of IndexStyle used to describe arrays which are optimally indexed by a Cartesian index. This is the default for new custom AbstractArray subtypes.

A Cartesian indexing style uses multiple integer indices to describe the position in a multidimensional array, with exactly one index per dimension. This means that requesting eachindex from an array that is IndexCartesian will return a range of CartesianIndices.

A N-dimensional custom array that reports its IndexStyle as IndexCartesian needs to implement indexing (and indexed assignment) with exactly N Int indices; all other indexing expressions — including linear indexing — will be recomputed to the equivalent Cartesian location. For example, if A were a 2×3 custom matrix with cartesian indexing, and we referenced A[5], this would be recomputed to the equivalent Cartesian index and call A[1, 3] since 5 = 2*1 + 3.

It is significantly more expensive to compute Cartesian indices from a linear index than it is to go the other way. The former operation requires division — a very costly operation — whereas the latter only uses multiplication and addition and is essentially free. This asymmetry means it is far more costly to use linear indexing with an IndexCartesian array than it is to use Cartesian indexing with an IndexLinear array.

See also IndexLinear.

source

Base.conj! — Function

  1. conj!(A)

Transform an array to its complex conjugate in-place.

See also conj.

Examples

  1. julia> A = [1+im 2-im; 2+2im 3+im]
  2. 2×2 Matrix{Complex{Int64}}:
  3. 1+1im 2-1im
  4. 2+2im 3+1im
  5. julia> conj!(A);
  6. julia> A
  7. 2×2 Matrix{Complex{Int64}}:
  8. 1-1im 2+1im
  9. 2-2im 3-1im

source

Base.stride — Function

  1. stride(A, k::Integer)

Return the distance in memory (in number of elements) between adjacent elements in dimension k.

See also: strides.

Examples

  1. julia> A = fill(1, (3,4,5));
  2. julia> stride(A,2)
  3. 3
  4. julia> stride(A,3)
  5. 12

source

Base.strides — Function

  1. strides(A)

Return a tuple of the memory strides in each dimension.

See also: stride.

Examples

  1. julia> A = fill(1, (3,4,5));
  2. julia> strides(A)
  3. (1, 3, 12)

source

Broadcast and vectorization

See also the dot syntax for vectorizing functions; for example, f.(args...) implicitly calls broadcast(f, args...). Rather than relying on “vectorized” methods of functions like sin to operate on arrays, you should use sin.(a) to vectorize via broadcast.

Base.Broadcast.broadcast — Function

  1. broadcast(f, As...)

Broadcast the function f over the arrays, tuples, collections, Refs and/or scalars As.

Broadcasting applies the function f over the elements of the container arguments and the scalars themselves in As. Singleton and missing dimensions are expanded to match the extents of the other arguments by virtually repeating the value. By default, only a limited number of types are considered scalars, including Numbers, Strings, Symbols, Types, Functions and some common singletons like missing and nothing. All other arguments are iterated over or indexed into elementwise.

The resulting container type is established by the following rules:

  • If all the arguments are scalars or zero-dimensional arrays, it returns an unwrapped scalar.
  • If at least one argument is a tuple and all others are scalars or zero-dimensional arrays, it returns a tuple.
  • All other combinations of arguments default to returning an Array, but custom container types can define their own implementation and promotion-like rules to customize the result when they appear as arguments.

A special syntax exists for broadcasting: f.(args...) is equivalent to broadcast(f, args...), and nested f.(g.(args...)) calls are fused into a single broadcast loop.

Examples

  1. julia> A = [1, 2, 3, 4, 5]
  2. 5-element Vector{Int64}:
  3. 1
  4. 2
  5. 3
  6. 4
  7. 5
  8. julia> B = [1 2; 3 4; 5 6; 7 8; 9 10]
  9. 5×2 Matrix{Int64}:
  10. 1 2
  11. 3 4
  12. 5 6
  13. 7 8
  14. 9 10
  15. julia> broadcast(+, A, B)
  16. 5×2 Matrix{Int64}:
  17. 2 3
  18. 5 6
  19. 8 9
  20. 11 12
  21. 14 15
  22. julia> parse.(Int, ["1", "2"])
  23. 2-element Vector{Int64}:
  24. 1
  25. 2
  26. julia> abs.((1, -2))
  27. (1, 2)
  28. julia> broadcast(+, 1.0, (0, -2.0))
  29. (1.0, -1.0)
  30. julia> (+).([[0,2], [1,3]], Ref{Vector{Int}}([1,-1]))
  31. 2-element Vector{Vector{Int64}}:
  32. [1, 1]
  33. [2, 2]
  34. julia> string.(("one","two","three","four"), ": ", 1:4)
  35. 4-element Vector{String}:
  36. "one: 1"
  37. "two: 2"
  38. "three: 3"
  39. "four: 4"

source

Base.Broadcast.broadcast! — Function

  1. broadcast!(f, dest, As...)

Like broadcast, but store the result of broadcast(f, As...) in the dest array. Note that dest is only used to store the result, and does not supply arguments to f unless it is also listed in the As, as in broadcast!(f, A, A, B) to perform A[:] = broadcast(f, A, B).

Examples

  1. julia> A = [1.0; 0.0]; B = [0.0; 0.0];
  2. julia> broadcast!(+, B, A, (0, -2.0));
  3. julia> B
  4. 2-element Vector{Float64}:
  5. 1.0
  6. -2.0
  7. julia> A
  8. 2-element Vector{Float64}:
  9. 1.0
  10. 0.0
  11. julia> broadcast!(+, A, A, (0, -2.0));
  12. julia> A
  13. 2-element Vector{Float64}:
  14. 1.0
  15. -2.0

source

Base.Broadcast.@__dot__ — Macro

  1. @. expr

Convert every function call or operator in expr into a “dot call” (e.g. convert f(x) to f.(x)), and convert every assignment in expr to a “dot assignment” (e.g. convert += to .+=).

If you want to avoid adding dots for selected function calls in expr, splice those function calls in with $. For example, @. sqrt(abs($sort(x))) is equivalent to sqrt.(abs.(sort(x))) (no dot for sort).

(@. is equivalent to a call to @__dot__.)

Examples

  1. julia> x = 1.0:3.0; y = similar(x);
  2. julia> @. y = x + 3 * sin(x)
  3. 3-element Vector{Float64}:
  4. 3.5244129544236893
  5. 4.727892280477045
  6. 3.4233600241796016

source

For specializing broadcast on custom types, see

Base.Broadcast.BroadcastStyle — Type

BroadcastStyle is an abstract type and trait-function used to determine behavior of objects under broadcasting. BroadcastStyle(typeof(x)) returns the style associated with x. To customize the broadcasting behavior of a type, one can declare a style by defining a type/method pair

  1. struct MyContainerStyle <: BroadcastStyle end
  2. Base.BroadcastStyle(::Type{<:MyContainer}) = MyContainerStyle()

One then writes method(s) (at least similar) operating on Broadcasted{MyContainerStyle}. There are also several pre-defined subtypes of BroadcastStyle that you may be able to leverage; see the Interfaces chapter for more information.

source

Base.Broadcast.AbstractArrayStyle — Type

Broadcast.AbstractArrayStyle{N} <: BroadcastStyle is the abstract supertype for any style associated with an AbstractArray type. The N parameter is the dimensionality, which can be handy for AbstractArray types that only support specific dimensionalities:

  1. struct SparseMatrixStyle <: Broadcast.AbstractArrayStyle{2} end
  2. Base.BroadcastStyle(::Type{<:SparseMatrixCSC}) = SparseMatrixStyle()

For AbstractArray types that support arbitrary dimensionality, N can be set to Any:

  1. struct MyArrayStyle <: Broadcast.AbstractArrayStyle{Any} end
  2. Base.BroadcastStyle(::Type{<:MyArray}) = MyArrayStyle()

In cases where you want to be able to mix multiple AbstractArrayStyles and keep track of dimensionality, your style needs to support a Val constructor:

  1. struct MyArrayStyleDim{N} <: Broadcast.AbstractArrayStyle{N} end
  2. (::Type{<:MyArrayStyleDim})(::Val{N}) where N = MyArrayStyleDim{N}()

Note that if two or more AbstractArrayStyle subtypes conflict, broadcasting machinery will fall back to producing Arrays. If this is undesirable, you may need to define binary BroadcastStyle rules to control the output type.

See also Broadcast.DefaultArrayStyle.

source

Base.Broadcast.ArrayStyle — Type

Broadcast.ArrayStyle{MyArrayType}() is a BroadcastStyle indicating that an object behaves as an array for broadcasting. It presents a simple way to construct Broadcast.AbstractArrayStyles for specific AbstractArray container types. Broadcast styles created this way lose track of dimensionality; if keeping track is important for your type, you should create your own custom Broadcast.AbstractArrayStyle.

source

Base.Broadcast.DefaultArrayStyle — Type

Broadcast.DefaultArrayStyle{N}() is a BroadcastStyle indicating that an object behaves as an N-dimensional array for broadcasting. Specifically, DefaultArrayStyle is used for any AbstractArray type that hasn’t defined a specialized style, and in the absence of overrides from other broadcast arguments the resulting output type is Array. When there are multiple inputs to broadcast, DefaultArrayStyle “loses” to any other Broadcast.ArrayStyle.

source

Base.Broadcast.broadcastable — Function

  1. Broadcast.broadcastable(x)

Return either x or an object like x such that it supports axes, indexing, and its type supports ndims.

If x supports iteration, the returned value should have the same axes and indexing behaviors as collect(x).

If x is not an AbstractArray but it supports axes, indexing, and its type supports ndims, then broadcastable(::typeof(x)) may be implemented to just return itself. Further, if x defines its own BroadcastStyle, then it must define its broadcastable method to return itself for the custom style to have any effect.

Examples

  1. julia> Broadcast.broadcastable([1,2,3]) # like `identity` since arrays already support axes and indexing
  2. 3-element Vector{Int64}:
  3. 1
  4. 2
  5. 3
  6. julia> Broadcast.broadcastable(Int) # Types don't support axes, indexing, or iteration but are commonly used as scalars
  7. Base.RefValue{Type{Int64}}(Int64)
  8. julia> Broadcast.broadcastable("hello") # Strings break convention of matching iteration and act like a scalar instead
  9. Base.RefValue{String}("hello")

source

Base.Broadcast.combine_axes — Function

  1. combine_axes(As...) -> Tuple

Determine the result axes for broadcasting across all values in As.

  1. julia> Broadcast.combine_axes([1], [1 2; 3 4; 5 6])
  2. (Base.OneTo(3), Base.OneTo(2))
  3. julia> Broadcast.combine_axes(1, 1, 1)
  4. ()

source

Base.Broadcast.combine_styles — Function

  1. combine_styles(cs...) -> BroadcastStyle

Decides which BroadcastStyle to use for any number of value arguments. Uses BroadcastStyle to get the style for each argument, and uses result_style to combine styles.

Examples

  1. julia> Broadcast.combine_styles([1], [1 2; 3 4])
  2. Base.Broadcast.DefaultArrayStyle{2}()

source

Base.Broadcast.result_style — Function

  1. result_style(s1::BroadcastStyle[, s2::BroadcastStyle]) -> BroadcastStyle

Takes one or two BroadcastStyles and combines them using BroadcastStyle to determine a common BroadcastStyle.

Examples

  1. julia> Broadcast.result_style(Broadcast.DefaultArrayStyle{0}(), Broadcast.DefaultArrayStyle{3}())
  2. Base.Broadcast.DefaultArrayStyle{3}()
  3. julia> Broadcast.result_style(Broadcast.Unknown(), Broadcast.DefaultArrayStyle{1}())
  4. Base.Broadcast.DefaultArrayStyle{1}()

source

Indexing and assignment

Base.getindex — Method

  1. getindex(A, inds...)

Return a subset of array A as specified by inds, where each ind may be, for example, an Int, an AbstractRange, or a Vector. See the manual section on array indexing for details.

Examples

  1. julia> A = [1 2; 3 4]
  2. 2×2 Matrix{Int64}:
  3. 1 2
  4. 3 4
  5. julia> getindex(A, 1)
  6. 1
  7. julia> getindex(A, [2, 1])
  8. 2-element Vector{Int64}:
  9. 3
  10. 1
  11. julia> getindex(A, 2:4)
  12. 3-element Vector{Int64}:
  13. 3
  14. 2
  15. 4

source

Base.setindex! — Method

  1. setindex!(A, X, inds...)
  2. A[inds...] = X

Store values from array X within some subset of A as specified by inds. The syntax A[inds...] = X is equivalent to (setindex!(A, X, inds...); X).

Examples

  1. julia> A = zeros(2,2);
  2. julia> setindex!(A, [10, 20], [1, 2]);
  3. julia> A[[3, 4]] = [30, 40];
  4. julia> A
  5. 2×2 Matrix{Float64}:
  6. 10.0 30.0
  7. 20.0 40.0

source

Base.copyto! — Method

  1. copyto!(dest, Rdest::CartesianIndices, src, Rsrc::CartesianIndices) -> dest

Copy the block of src in the range of Rsrc to the block of dest in the range of Rdest. The sizes of the two regions must match.

Examples

  1. julia> A = zeros(5, 5);
  2. julia> B = [1 2; 3 4];
  3. julia> Ainds = CartesianIndices((2:3, 2:3));
  4. julia> Binds = CartesianIndices(B);
  5. julia> copyto!(A, Ainds, B, Binds)
  6. 5×5 Matrix{Float64}:
  7. 0.0 0.0 0.0 0.0 0.0
  8. 0.0 1.0 2.0 0.0 0.0
  9. 0.0 3.0 4.0 0.0 0.0
  10. 0.0 0.0 0.0 0.0 0.0
  11. 0.0 0.0 0.0 0.0 0.0

source

Base.copy! — Function

  1. copy!(dst, src) -> dst

In-place copy of src into dst, discarding any pre-existing elements in dst. If dst and src are of the same type, dst == src should hold after the call. If dst and src are multidimensional arrays, they must have equal axes.

See also copyto!.

Julia 1.1

This method requires at least Julia 1.1. In Julia 1.0 this method is available from the Future standard library as Future.copy!.

source

Base.isassigned — Function

  1. isassigned(array, i) -> Bool

Test whether the given array has a value associated with index i. Return false if the index is out of bounds, or has an undefined reference.

Examples

  1. julia> isassigned(rand(3, 3), 5)
  2. true
  3. julia> isassigned(rand(3, 3), 3 * 3 + 1)
  4. false
  5. julia> mutable struct Foo end
  6. julia> v = similar(rand(3), Foo)
  7. 3-element Vector{Foo}:
  8. #undef
  9. #undef
  10. #undef
  11. julia> isassigned(v, 1)
  12. false

source

Base.Colon — Type

  1. Colon()

Colons (:) are used to signify indexing entire objects or dimensions at once.

Very few operations are defined on Colons directly; instead they are converted by to_indices to an internal vector type (Base.Slice) to represent the collection of indices they span before being used.

The singleton instance of Colon is also a function used to construct ranges; see :.

source

Base.IteratorsMD.CartesianIndex — Type

  1. CartesianIndex(i, j, k...) -> I
  2. CartesianIndex((i, j, k...)) -> I

Create a multidimensional index I, which can be used for indexing a multidimensional array A. In particular, A[I] is equivalent to A[i,j,k...]. One can freely mix integer and CartesianIndex indices; for example, A[Ipre, i, Ipost] (where Ipre and Ipost are CartesianIndex indices and i is an Int) can be a useful expression when writing algorithms that work along a single dimension of an array of arbitrary dimensionality.

A CartesianIndex is sometimes produced by eachindex, and always when iterating with an explicit CartesianIndices.

Examples

  1. julia> A = reshape(Vector(1:16), (2, 2, 2, 2))
  2. 2×2×2×2 Array{Int64, 4}:
  3. [:, :, 1, 1] =
  4. 1 3
  5. 2 4
  6. [:, :, 2, 1] =
  7. 5 7
  8. 6 8
  9. [:, :, 1, 2] =
  10. 9 11
  11. 10 12
  12. [:, :, 2, 2] =
  13. 13 15
  14. 14 16
  15. julia> A[CartesianIndex((1, 1, 1, 1))]
  16. 1
  17. julia> A[CartesianIndex((1, 1, 1, 2))]
  18. 9
  19. julia> A[CartesianIndex((1, 1, 2, 1))]
  20. 5

source

Base.IteratorsMD.CartesianIndices — Type

  1. CartesianIndices(sz::Dims) -> R
  2. CartesianIndices((istart:[istep:]istop, jstart:[jstep:]jstop, ...)) -> R

Define a region R spanning a multidimensional rectangular range of integer indices. These are most commonly encountered in the context of iteration, where for I in R ... end will return CartesianIndex indices I equivalent to the nested loops

  1. for j = jstart:jstep:jstop
  2. for i = istart:istep:istop
  3. ...
  4. end
  5. end

Consequently these can be useful for writing algorithms that work in arbitrary dimensions.

  1. CartesianIndices(A::AbstractArray) -> R

As a convenience, constructing a CartesianIndices from an array makes a range of its indices.

Julia 1.6

The step range method CartesianIndices((istart:istep:istop, jstart:[jstep:]jstop, ...)) requires at least Julia 1.6.

Examples

  1. julia> foreach(println, CartesianIndices((2, 2, 2)))
  2. CartesianIndex(1, 1, 1)
  3. CartesianIndex(2, 1, 1)
  4. CartesianIndex(1, 2, 1)
  5. CartesianIndex(2, 2, 1)
  6. CartesianIndex(1, 1, 2)
  7. CartesianIndex(2, 1, 2)
  8. CartesianIndex(1, 2, 2)
  9. CartesianIndex(2, 2, 2)
  10. julia> CartesianIndices(fill(1, (2,3)))
  11. CartesianIndices((2, 3))

Conversion between linear and cartesian indices

Linear index to cartesian index conversion exploits the fact that a CartesianIndices is an AbstractArray and can be indexed linearly:

  1. julia> cartesian = CartesianIndices((1:3, 1:2))
  2. CartesianIndices((1:3, 1:2))
  3. julia> cartesian[4]
  4. CartesianIndex(1, 2)
  5. julia> cartesian = CartesianIndices((1:2:5, 1:2))
  6. CartesianIndices((1:2:5, 1:2))
  7. julia> cartesian[2, 2]
  8. CartesianIndex(3, 2)

Broadcasting

CartesianIndices support broadcasting arithmetic (+ and -) with a CartesianIndex.

Julia 1.1

Broadcasting of CartesianIndices requires at least Julia 1.1.

  1. julia> CIs = CartesianIndices((2:3, 5:6))
  2. CartesianIndices((2:3, 5:6))
  3. julia> CI = CartesianIndex(3, 4)
  4. CartesianIndex(3, 4)
  5. julia> CIs .+ CI
  6. CartesianIndices((5:6, 9:10))

For cartesian to linear index conversion, see LinearIndices.

source

Base.Dims — Type

  1. Dims{N}

An NTuple of N Ints used to represent the dimensions of an AbstractArray.

source

Base.LinearIndices — Type

  1. LinearIndices(A::AbstractArray)

Return a LinearIndices array with the same shape and axes as A, holding the linear index of each entry in A. Indexing this array with cartesian indices allows mapping them to linear indices.

For arrays with conventional indexing (indices start at 1), or any multidimensional array, linear indices range from 1 to length(A). However, for AbstractVectors linear indices are axes(A, 1), and therefore do not start at 1 for vectors with unconventional indexing.

Calling this function is the “safe” way to write algorithms that exploit linear indexing.

Examples

  1. julia> A = fill(1, (5,6,7));
  2. julia> b = LinearIndices(A);
  3. julia> extrema(b)
  4. (1, 210)
  1. LinearIndices(inds::CartesianIndices) -> R
  2. LinearIndices(sz::Dims) -> R
  3. LinearIndices((istart:istop, jstart:jstop, ...)) -> R

Return a LinearIndices array with the specified shape or axes.

Example

The main purpose of this constructor is intuitive conversion from cartesian to linear indexing:

  1. julia> linear = LinearIndices((1:3, 1:2))
  2. 3×2 LinearIndices{2, Tuple{UnitRange{Int64}, UnitRange{Int64}}}:
  3. 1 4
  4. 2 5
  5. 3 6
  6. julia> linear[1,2]
  7. 4

source

Base.to_indices — Function

  1. to_indices(A, I::Tuple)

Convert the tuple I to a tuple of indices for use in indexing into array A.

The returned tuple must only contain either Ints or AbstractArrays of scalar indices that are supported by array A. It will error upon encountering a novel index type that it does not know how to process.

For simple index types, it defers to the unexported Base.to_index(A, i) to process each index i. While this internal function is not intended to be called directly, Base.to_index may be extended by custom array or index types to provide custom indexing behaviors.

More complicated index types may require more context about the dimension into which they index. To support those cases, to_indices(A, I) calls to_indices(A, axes(A), I), which then recursively walks through both the given tuple of indices and the dimensional indices of A in tandem. As such, not all index types are guaranteed to propagate to Base.to_index.

Examples

  1. julia> A = zeros(1,2,3,4);
  2. julia> to_indices(A, (1,1,2,2))
  3. (1, 1, 2, 2)
  4. julia> to_indices(A, (1,1,2,20)) # no bounds checking
  5. (1, 1, 2, 20)
  6. julia> to_indices(A, (CartesianIndex((1,)), 2, CartesianIndex((3,4)))) # exotic index
  7. (1, 2, 3, 4)
  8. julia> to_indices(A, ([1,1], 1:2, 3, 4))
  9. ([1, 1], 1:2, 3, 4)
  10. julia> to_indices(A, (1,2)) # no shape checking
  11. (1, 2)

source

Base.checkbounds — Function

  1. checkbounds(Bool, A, I...)

Return true if the specified indices I are in bounds for the given array A. Subtypes of AbstractArray should specialize this method if they need to provide custom bounds checking behaviors; however, in many cases one can rely on A‘s indices and checkindex.

See also checkindex.

Examples

  1. julia> A = rand(3, 3);
  2. julia> checkbounds(Bool, A, 2)
  3. true
  4. julia> checkbounds(Bool, A, 3, 4)
  5. false
  6. julia> checkbounds(Bool, A, 1:3)
  7. true
  8. julia> checkbounds(Bool, A, 1:3, 2:4)
  9. false

source

  1. checkbounds(A, I...)

Throw an error if the specified indices I are not in bounds for the given array A.

source

Base.checkindex — Function

  1. checkindex(Bool, inds::AbstractUnitRange, index)

Return true if the given index is within the bounds of inds. Custom types that would like to behave as indices for all arrays can extend this method in order to provide a specialized bounds checking implementation.

See also checkbounds.

Examples

  1. julia> checkindex(Bool, 1:20, 8)
  2. true
  3. julia> checkindex(Bool, 1:20, 21)
  4. false

source

Base.elsize — Function

  1. elsize(type)

Compute the memory stride in bytes between consecutive elements of eltype stored inside the given type, if the array elements are stored densely with a uniform linear stride.

Examples

  1. julia> Base.elsize(rand(Float32, 10))
  2. 4

source

Views (SubArrays and other view types))

A “view” is a data structure that acts like an array (it is a subtype of AbstractArray), but the underlying data is actually part of another array.

For example, if x is an array and v = @view x[1:10], then v acts like a 10-element array, but its data is actually accessing the first 10 elements of x. Writing to a view, e.g. v[3] = 2, writes directly to the underlying array x (in this case modifying x[3]).

Slicing operations like x[1:10] create a copy by default in Julia. @view x[1:10] changes it to make a view. The @views macro can be used on a whole block of code (e.g. @views function foo() .... end or @views begin ... end) to change all the slicing operations in that block to use views. Sometimes making a copy of the data is faster and sometimes using a view is faster, as described in the performance tips.

Base.view — Function

  1. view(A, inds...)

Like getindex, but returns a lightweight array that lazily references (or is effectively a view into) the parent array A at the given index or indices inds instead of eagerly extracting elements or constructing a copied subset. Calling getindex or setindex! on the returned value (often a SubArray) computes the indices to access or modify the parent array on the fly. The behavior is undefined if the shape of the parent array is changed after view is called because there is no bound check for the parent array; e.g., it may cause a segmentation fault.

Some immutable parent arrays (like ranges) may choose to simply recompute a new array in some circumstances instead of returning a SubArray if doing so is efficient and provides compatible semantics.

Julia 1.6

In Julia 1.6 or later, view can be called on an AbstractString, returning a SubString.

Examples

  1. julia> A = [1 2; 3 4]
  2. 2×2 Matrix{Int64}:
  3. 1 2
  4. 3 4
  5. julia> b = view(A, :, 1)
  6. 2-element view(::Matrix{Int64}, :, 1) with eltype Int64:
  7. 1
  8. 3
  9. julia> fill!(b, 0)
  10. 2-element view(::Matrix{Int64}, :, 1) with eltype Int64:
  11. 0
  12. 0
  13. julia> A # Note A has changed even though we modified b
  14. 2×2 Matrix{Int64}:
  15. 0 2
  16. 0 4
  17. julia> view(2:5, 2:3) # returns a range as type is immutable
  18. 3:4

source

Base.@view — Macro

  1. @view A[inds...]

Transform the indexing expression A[inds...] into the equivalent view call.

This can only be applied directly to a single indexing expression and is particularly helpful for expressions that include the special begin or end indexing syntaxes like A[begin, 2:end-1] (as those are not supported by the normal view function).

Note that @view cannot be used as the target of a regular assignment (e.g., @view(A[1, 2:end]) = ...), nor would the un-decorated indexed assignment (A[1, 2:end] = ...) or broadcasted indexed assignment (A[1, 2:end] .= ...) make a copy. It can be useful, however, for updating broadcasted assignments like @view(A[1, 2:end]) .+= 1 because this is a simple syntax for @view(A[1, 2:end]) .= @view(A[1, 2:end]) + 1, and the indexing expression on the right-hand side would otherwise make a copy without the @view.

See also @views to switch an entire block of code to use views for non-scalar indexing.

Julia 1.5

Using begin in an indexing expression to refer to the first index requires at least Julia 1.5.

Examples

  1. julia> A = [1 2; 3 4]
  2. 2×2 Matrix{Int64}:
  3. 1 2
  4. 3 4
  5. julia> b = @view A[:, 1]
  6. 2-element view(::Matrix{Int64}, :, 1) with eltype Int64:
  7. 1
  8. 3
  9. julia> fill!(b, 0)
  10. 2-element view(::Matrix{Int64}, :, 1) with eltype Int64:
  11. 0
  12. 0
  13. julia> A
  14. 2×2 Matrix{Int64}:
  15. 0 2
  16. 0 4

source

Base.@views — Macro

  1. @views expression

Convert every array-slicing operation in the given expression (which may be a begin/end block, loop, function, etc.) to return a view. Scalar indices, non-array types, and explicit getindex calls (as opposed to array[...]) are unaffected.

Similarly, @views converts string slices into SubString views.

Note

The @views macro only affects array[...] expressions that appear explicitly in the given expression, not array slicing that occurs in functions called by that code.

Julia 1.5

Using begin in an indexing expression to refer to the first index requires at least Julia 1.5.

Examples

  1. julia> A = zeros(3, 3);
  2. julia> @views for row in 1:3
  3. b = A[row, :]
  4. b[:] .= row
  5. end
  6. julia> A
  7. 3×3 Matrix{Float64}:
  8. 1.0 1.0 1.0
  9. 2.0 2.0 2.0
  10. 3.0 3.0 3.0

source

Base.parent — Function

  1. parent(A)

Return the underlying “parent array”. This parent array of objects of types SubArray, ReshapedArray or LinearAlgebra.Transpose is what was passed as an argument to view, reshape, transpose, etc. during object creation. If the input is not a wrapped object, return the input itself. If the input is wrapped multiple times, only the outermost wrapper will be removed.

Examples

  1. julia> A = [1 2; 3 4]
  2. 2×2 Matrix{Int64}:
  3. 1 2
  4. 3 4
  5. julia> V = view(A, 1:2, :)
  6. 2×2 view(::Matrix{Int64}, 1:2, :) with eltype Int64:
  7. 1 2
  8. 3 4
  9. julia> parent(V)
  10. 2×2 Matrix{Int64}:
  11. 1 2
  12. 3 4

source

Base.parentindices — Function

  1. parentindices(A)

Return the indices in the parent which correspond to the array view A.

Examples

  1. julia> A = [1 2; 3 4];
  2. julia> V = view(A, 1, :)
  3. 2-element view(::Matrix{Int64}, 1, :) with eltype Int64:
  4. 1
  5. 2
  6. julia> parentindices(V)
  7. (1, Base.Slice(Base.OneTo(2)))

source

Base.selectdim — Function

  1. selectdim(A, d::Integer, i)

Return a view of all the data of A where the index for dimension d equals i.

Equivalent to view(A,:,:,...,i,:,:,...) where i is in position d.

See also: eachslice.

Examples

  1. julia> A = [1 2 3 4; 5 6 7 8]
  2. 2×4 Matrix{Int64}:
  3. 1 2 3 4
  4. 5 6 7 8
  5. julia> selectdim(A, 2, 3)
  6. 2-element view(::Matrix{Int64}, :, 3) with eltype Int64:
  7. 3
  8. 7
  9. julia> selectdim(A, 2, 3:4)
  10. 2×2 view(::Matrix{Int64}, :, 3:4) with eltype Int64:
  11. 3 4
  12. 7 8

source

Base.reinterpret — Function

  1. reinterpret(type, A)

Change the type-interpretation of the binary data in the primitive type A to that of the primitive type type. The size of type has to be the same as that of the type of A. For example, reinterpret(Float32, UInt32(7)) interprets the 4 bytes corresponding to UInt32(7) as a Float32.

Examples

  1. julia> reinterpret(Float32, UInt32(7))
  2. 1.0f-44

source

  1. reinterpret(reshape, T, A::AbstractArray{S}) -> B

Change the type-interpretation of A while consuming or adding a “channel dimension.”

If sizeof(T) = n*sizeof(S) for n>1, A‘s first dimension must be of size n and B lacks A‘s first dimension. Conversely, if sizeof(S) = n*sizeof(T) for n>1, B gets a new first dimension of size n. The dimensionality is unchanged if sizeof(T) == sizeof(S).

Julia 1.6

This method requires at least Julia 1.6.

Examples

  1. julia> A = [1 2; 3 4]
  2. 2×2 Matrix{Int64}:
  3. 1 2
  4. 3 4
  5. julia> reinterpret(reshape, Complex{Int}, A) # the result is a vector
  6. 2-element reinterpret(reshape, Complex{Int64}, ::Matrix{Int64}) with eltype Complex{Int64}:
  7. 1 + 3im
  8. 2 + 4im
  9. julia> a = [(1,2,3), (4,5,6)]
  10. 2-element Vector{Tuple{Int64, Int64, Int64}}:
  11. (1, 2, 3)
  12. (4, 5, 6)
  13. julia> reinterpret(reshape, Int, a) # the result is a matrix
  14. 3×2 reinterpret(reshape, Int64, ::Vector{Tuple{Int64, Int64, Int64}}) with eltype Int64:
  15. 1 4
  16. 2 5
  17. 3 6

source

Base.reshape — Function

  1. reshape(A, dims...) -> AbstractArray
  2. reshape(A, dims) -> AbstractArray

Return an array with the same data as A, but with different dimension sizes or number of dimensions. The two arrays share the same underlying data, so that the result is mutable if and only if A is mutable, and setting elements of one alters the values of the other.

The new dimensions may be specified either as a list of arguments or as a shape tuple. At most one dimension may be specified with a :, in which case its length is computed such that its product with all the specified dimensions is equal to the length of the original array A. The total number of elements must not change.

Examples

  1. julia> A = Vector(1:16)
  2. 16-element Vector{Int64}:
  3. 1
  4. 2
  5. 3
  6. 4
  7. 5
  8. 6
  9. 7
  10. 8
  11. 9
  12. 10
  13. 11
  14. 12
  15. 13
  16. 14
  17. 15
  18. 16
  19. julia> reshape(A, (4, 4))
  20. 4×4 Matrix{Int64}:
  21. 1 5 9 13
  22. 2 6 10 14
  23. 3 7 11 15
  24. 4 8 12 16
  25. julia> reshape(A, 2, :)
  26. 2×8 Matrix{Int64}:
  27. 1 3 5 7 9 11 13 15
  28. 2 4 6 8 10 12 14 16
  29. julia> reshape(1:6, 2, 3)
  30. 2×3 reshape(::UnitRange{Int64}, 2, 3) with eltype Int64:
  31. 1 3 5
  32. 2 4 6

source

Base.dropdims — Function

  1. dropdims(A; dims)

Return an array with the same data as A, but with the dimensions specified by dims removed. size(A,d) must equal 1 for every d in dims, and repeated dimensions or numbers outside 1:ndims(A) are forbidden.

The result shares the same underlying data as A, such that the result is mutable if and only if A is mutable, and setting elements of one alters the values of the other.

See also: reshape, vec.

Examples

  1. julia> a = reshape(Vector(1:4),(2,2,1,1))
  2. 2×2×1×1 Array{Int64, 4}:
  3. [:, :, 1, 1] =
  4. 1 3
  5. 2 4
  6. julia> b = dropdims(a; dims=3)
  7. 2×2×1 Array{Int64, 3}:
  8. [:, :, 1] =
  9. 1 3
  10. 2 4
  11. julia> b[1,1,1] = 5; a
  12. 2×2×1×1 Array{Int64, 4}:
  13. [:, :, 1, 1] =
  14. 5 3
  15. 2 4

source

Base.vec — Function

  1. vec(a::AbstractArray) -> AbstractVector

Reshape the array a as a one-dimensional column vector. Return a if it is already an AbstractVector. The resulting array shares the same underlying data as a, so it will only be mutable if a is mutable, in which case modifying one will also modify the other.

Examples

  1. julia> a = [1 2 3; 4 5 6]
  2. 2×3 Matrix{Int64}:
  3. 1 2 3
  4. 4 5 6
  5. julia> vec(a)
  6. 6-element Vector{Int64}:
  7. 1
  8. 4
  9. 2
  10. 5
  11. 3
  12. 6
  13. julia> vec(1:3)
  14. 1:3

See also reshape, dropdims.

source

Base.SubArray — Type

  1. SubArray{T,N,P,I,L} <: AbstractArray{T,N}

N-dimensional view into a parent array (of type P) with an element type T, restricted by a tuple of indices (of type I). L is true for types that support fast linear indexing, and false otherwise.

Construct SubArrays using the view function.

source

Concatenation and permutation

Base.cat — Function

  1. cat(A...; dims)

Concatenate the input arrays along the dimensions specified in dims.

Along a dimension d in dims, the size of the output array is sum(size(a,d) for a in A). Along other dimensions, all input arrays should have the same size, which will also be the size of the output array along those dimensions.

If dims is a single number, the different arrays are tightly packed along that dimension. If dims is an iterable containing several dimensions, the positions along these dimensions are increased simultaneously for each input array, filling with zero elsewhere. This allows one to construct block-diagonal matrices as cat(matrices...; dims=(1,2)), and their higher-dimensional analogues.

The special case dims=1 is vcat, and dims=2 is hcat. See also hvcat, hvncat, stack, repeat.

The keyword also accepts Val(dims).

Julia 1.8

For multiple dimensions dims = Val(::Tuple) was added in Julia 1.8.

Examples

  1. julia> cat([1 2; 3 4], [pi, pi], fill(10, 2,3,1); dims=2) # same as hcat
  2. 2×6×1 Array{Float64, 3}:
  3. [:, :, 1] =
  4. 1.0 2.0 3.14159 10.0 10.0 10.0
  5. 3.0 4.0 3.14159 10.0 10.0 10.0
  6. julia> cat(true, trues(2,2), trues(4)', dims=(1,2)) # block-diagonal
  7. 4×7 Matrix{Bool}:
  8. 1 0 0 0 0 0 0
  9. 0 1 1 0 0 0 0
  10. 0 1 1 0 0 0 0
  11. 0 0 0 1 1 1 1
  12. julia> cat(1, [2], [3;;]; dims=Val(2))
  13. 1×3 Matrix{Int64}:
  14. 1 2 3

source

Base.vcat — Function

  1. vcat(A...)

Concatenate arrays or numbers vertically. Equivalent to cat(A...; dims=1), and to the syntax [a; b; c].

To concatenate a large vector of arrays, reduce(vcat, A) calls an efficient method when A isa AbstractVector{<:AbstractVecOrMat}, rather than working pairwise.

See also hcat, Iterators.flatten, stack.

Examples

  1. julia> v = vcat([1,2], [3,4])
  2. 4-element Vector{Int64}:
  3. 1
  4. 2
  5. 3
  6. 4
  7. julia> v == vcat(1, 2, [3,4]) # accepts numbers
  8. true
  9. julia> v == [1; 2; [3,4]] # syntax for the same operation
  10. true
  11. julia> summary(ComplexF64[1; 2; [3,4]]) # syntax for supplying the element type
  12. "4-element Vector{ComplexF64}"
  13. julia> vcat(range(1, 2, length=3)) # collects lazy ranges
  14. 3-element Vector{Float64}:
  15. 1.0
  16. 1.5
  17. 2.0
  18. julia> two = ([10, 20, 30]', Float64[4 5 6; 7 8 9]) # row vector and a matrix
  19. ([10 20 30], [4.0 5.0 6.0; 7.0 8.0 9.0])
  20. julia> vcat(two...)
  21. 3×3 Matrix{Float64}:
  22. 10.0 20.0 30.0
  23. 4.0 5.0 6.0
  24. 7.0 8.0 9.0
  25. julia> vs = [[1, 2], [3, 4], [5, 6]];
  26. julia> reduce(vcat, vs) # more efficient than vcat(vs...)
  27. 6-element Vector{Int64}:
  28. 1
  29. 2
  30. 3
  31. 4
  32. 5
  33. 6
  34. julia> ans == collect(Iterators.flatten(vs))
  35. true

source

Base.hcat — Function

  1. hcat(A...)

Concatenate arrays or numbers horizontally. Equivalent to cat(A...; dims=2), and to the syntax [a b c] or [a;; b;; c].

For a large vector of arrays, reduce(hcat, A) calls an efficient method when A isa AbstractVector{<:AbstractVecOrMat}. For a vector of vectors, this can also be written stack(A).

See also vcat, hvcat.

Examples

  1. julia> hcat([1,2], [3,4], [5,6])
  2. 2×3 Matrix{Int64}:
  3. 1 3 5
  4. 2 4 6
  5. julia> hcat(1, 2, [30 40], [5, 6, 7]') # accepts numbers
  6. 1×7 Matrix{Int64}:
  7. 1 2 30 40 5 6 7
  8. julia> ans == [1 2 [30 40] [5, 6, 7]'] # syntax for the same operation
  9. true
  10. julia> Float32[1 2 [30 40] [5, 6, 7]'] # syntax for supplying the eltype
  11. 1×7 Matrix{Float32}:
  12. 1.0 2.0 30.0 40.0 5.0 6.0 7.0
  13. julia> ms = [zeros(2,2), [1 2; 3 4], [50 60; 70 80]];
  14. julia> reduce(hcat, ms) # more efficient than hcat(ms...)
  15. 2×6 Matrix{Float64}:
  16. 0.0 0.0 1.0 2.0 50.0 60.0
  17. 0.0 0.0 3.0 4.0 70.0 80.0
  18. julia> stack(ms) |> summary # disagrees on a vector of matrices
  19. "2×2×3 Array{Float64, 3}"
  20. julia> hcat(Int[], Int[], Int[]) # empty vectors, each of size (0,)
  21. 0×3 Matrix{Int64}
  22. julia> hcat([1.1, 9.9], Matrix(undef, 2, 0)) # hcat with empty 2×0 Matrix
  23. 2×1 Matrix{Any}:
  24. 1.1
  25. 9.9

source

Base.hvcat — Function

  1. hvcat(blocks_per_row::Union{Tuple{Vararg{Int}}, Int}, values...)

Horizontal and vertical concatenation in one call. This function is called for block matrix syntax. The first argument specifies the number of arguments to concatenate in each block row. If the first argument is a single integer n, then all block rows are assumed to have n block columns.

Examples

  1. julia> a, b, c, d, e, f = 1, 2, 3, 4, 5, 6
  2. (1, 2, 3, 4, 5, 6)
  3. julia> [a b c; d e f]
  4. 2×3 Matrix{Int64}:
  5. 1 2 3
  6. 4 5 6
  7. julia> hvcat((3,3), a,b,c,d,e,f)
  8. 2×3 Matrix{Int64}:
  9. 1 2 3
  10. 4 5 6
  11. julia> [a b; c d; e f]
  12. 3×2 Matrix{Int64}:
  13. 1 2
  14. 3 4
  15. 5 6
  16. julia> hvcat((2,2,2), a,b,c,d,e,f)
  17. 3×2 Matrix{Int64}:
  18. 1 2
  19. 3 4
  20. 5 6
  21. julia> hvcat((2,2,2), a,b,c,d,e,f) == hvcat(2, a,b,c,d,e,f)
  22. true

source

Base.hvncat — Function

  1. hvncat(dim::Int, row_first, values...)
  2. hvncat(dims::Tuple{Vararg{Int}}, row_first, values...)
  3. hvncat(shape::Tuple{Vararg{Tuple}}, row_first, values...)

Horizontal, vertical, and n-dimensional concatenation of many values in one call.

This function is called for block matrix syntax. The first argument either specifies the shape of the concatenation, similar to hvcat, as a tuple of tuples, or the dimensions that specify the key number of elements along each axis, and is used to determine the output dimensions. The dims form is more performant, and is used by default when the concatenation operation has the same number of elements along each axis (e.g., [a b; c d;;; e f ; g h]). The shape form is used when the number of elements along each axis is unbalanced (e.g., [a b ; c]). Unbalanced syntax needs additional validation overhead. The dim form is an optimization for concatenation along just one dimension. row_first indicates how values are ordered. The meaning of the first and second elements of shape are also swapped based on row_first.

Examples

  1. julia> a, b, c, d, e, f = 1, 2, 3, 4, 5, 6
  2. (1, 2, 3, 4, 5, 6)
  3. julia> [a b c;;; d e f]
  4. 1×3×2 Array{Int64, 3}:
  5. [:, :, 1] =
  6. 1 2 3
  7. [:, :, 2] =
  8. 4 5 6
  9. julia> hvncat((2,1,3), false, a,b,c,d,e,f)
  10. 2×1×3 Array{Int64, 3}:
  11. [:, :, 1] =
  12. 1
  13. 2
  14. [:, :, 2] =
  15. 3
  16. 4
  17. [:, :, 3] =
  18. 5
  19. 6
  20. julia> [a b;;; c d;;; e f]
  21. 1×2×3 Array{Int64, 3}:
  22. [:, :, 1] =
  23. 1 2
  24. [:, :, 2] =
  25. 3 4
  26. [:, :, 3] =
  27. 5 6
  28. julia> hvncat(((3, 3), (3, 3), (6,)), true, a, b, c, d, e, f)
  29. 1×3×2 Array{Int64, 3}:
  30. [:, :, 1] =
  31. 1 2 3
  32. [:, :, 2] =
  33. 4 5 6

Examples for construction of the arguments

  1. [a b c ; d e f ;;;
  2. g h i ; j k l ;;;
  3. m n o ; p q r ;;;
  4. s t u ; v w x]
  5. dims = (2, 3, 4)
  6. [a b ; c ;;; d ;;;;]
  7. ___ _ _
  8. 2 1 1 = elements in each row (2, 1, 1)
  9. _______ _
  10. 3 1 = elements in each column (3, 1)
  11. _____________
  12. 4 = elements in each 3d slice (4,)
  13. _____________
  14. 4 = elements in each 4d slice (4,)
  15. shape = ((2, 1, 1), (3, 1), (4,), (4,)) with `row_first` = true

source

Base.stack — Function

  1. stack(iter; [dims])

Combine a collection of arrays (or other iterable objects) of equal size into one larger array, by arranging them along one or more new dimensions.

By default the axes of the elements are placed first, giving size(result) = (size(first(iter))..., size(iter)...). This has the same order of elements as Iterators.flatten(iter).

With keyword dims::Integer, instead the ith element of iter becomes the slice selectdim(result, dims, i), so that size(result, dims) == length(iter). In this case stack reverses the action of eachslice with the same dims.

The various cat functions also combine arrays. However, these all extend the arrays’ existing (possibly trivial) dimensions, rather than placing the arrays along new dimensions. They also accept arrays as separate arguments, rather than a single collection.

Julia 1.9

This function requires at least Julia 1.9.

Examples

  1. julia> vecs = (1:2, [30, 40], Float32[500, 600]);
  2. julia> mat = stack(vecs)
  3. 2×3 Matrix{Float32}:
  4. 1.0 30.0 500.0
  5. 2.0 40.0 600.0
  6. julia> mat == hcat(vecs...) == reduce(hcat, collect(vecs))
  7. true
  8. julia> vec(mat) == vcat(vecs...) == reduce(vcat, collect(vecs))
  9. true
  10. julia> stack(zip(1:4, 10:99)) # accepts any iterators of iterators
  11. 2×4 Matrix{Int64}:
  12. 1 2 3 4
  13. 10 11 12 13
  14. julia> vec(ans) == collect(Iterators.flatten(zip(1:4, 10:99)))
  15. true
  16. julia> stack(vecs; dims=1) # unlike any cat function, 1st axis of vecs[1] is 2nd axis of result
  17. 3×2 Matrix{Float32}:
  18. 1.0 2.0
  19. 30.0 40.0
  20. 500.0 600.0
  21. julia> x = rand(3,4);
  22. julia> x == stack(eachcol(x)) == stack(eachrow(x), dims=1) # inverse of eachslice
  23. true

Higher-dimensional examples:

  1. julia> A = rand(5, 7, 11);
  2. julia> E = eachslice(A, dims=2); # a vector of matrices
  3. julia> (element = size(first(E)), container = size(E))
  4. (element = (5, 11), container = (7,))
  5. julia> stack(E) |> size
  6. (5, 11, 7)
  7. julia> stack(E) == stack(E; dims=3) == cat(E...; dims=3)
  8. true
  9. julia> A == stack(E; dims=2)
  10. true
  11. julia> M = (fill(10i+j, 2, 3) for i in 1:5, j in 1:7);
  12. julia> (element = size(first(M)), container = size(M))
  13. (element = (2, 3), container = (5, 7))
  14. julia> stack(M) |> size # keeps all dimensions
  15. (2, 3, 5, 7)
  16. julia> stack(M; dims=1) |> size # vec(container) along dims=1
  17. (35, 2, 3)
  18. julia> hvcat(5, M...) |> size # hvcat puts matrices next to each other
  19. (14, 15)

source

  1. stack(f, args...; [dims])

Apply a function to each element of a collection, and stack the result. Or to several collections, zipped together.

The function should return arrays (or tuples, or other iterators) all of the same size. These become slices of the result, each separated along dims (if given) or by default along the last dimensions.

See also mapslices, eachcol.

Examples

  1. julia> stack(c -> (c, c-32), "julia")
  2. 2×5 Matrix{Char}:
  3. 'j' 'u' 'l' 'i' 'a'
  4. 'J' 'U' 'L' 'I' 'A'
  5. julia> stack(eachrow([1 2 3; 4 5 6]), (10, 100); dims=1) do row, n
  6. vcat(row, row .* n, row ./ n)
  7. end
  8. 2×9 Matrix{Float64}:
  9. 1.0 2.0 3.0 10.0 20.0 30.0 0.1 0.2 0.3
  10. 4.0 5.0 6.0 400.0 500.0 600.0 0.04 0.05 0.06

source

Base.vect — Function

  1. vect(X...)

Create a Vector with element type computed from the promote_typeof of the argument, containing the argument list.

Examples

  1. julia> a = Base.vect(UInt8(1), 2.5, 1//2)
  2. 3-element Vector{Float64}:
  3. 1.0
  4. 2.5
  5. 0.5

source

Base.circshift — Function

  1. circshift(A, shifts)

Circularly shift, i.e. rotate, the data in an array. The second argument is a tuple or vector giving the amount to shift in each dimension, or an integer to shift only in the first dimension.

See also: circshift!, circcopy!, bitrotate, <<.

Examples

  1. julia> b = reshape(Vector(1:16), (4,4))
  2. 4×4 Matrix{Int64}:
  3. 1 5 9 13
  4. 2 6 10 14
  5. 3 7 11 15
  6. 4 8 12 16
  7. julia> circshift(b, (0,2))
  8. 4×4 Matrix{Int64}:
  9. 9 13 1 5
  10. 10 14 2 6
  11. 11 15 3 7
  12. 12 16 4 8
  13. julia> circshift(b, (-1,0))
  14. 4×4 Matrix{Int64}:
  15. 2 6 10 14
  16. 3 7 11 15
  17. 4 8 12 16
  18. 1 5 9 13
  19. julia> a = BitArray([true, true, false, false, true])
  20. 5-element BitVector:
  21. 1
  22. 1
  23. 0
  24. 0
  25. 1
  26. julia> circshift(a, 1)
  27. 5-element BitVector:
  28. 1
  29. 1
  30. 1
  31. 0
  32. 0
  33. julia> circshift(a, -1)
  34. 5-element BitVector:
  35. 1
  36. 0
  37. 0
  38. 1
  39. 1

source

Base.circshift! — Function

  1. circshift!(dest, src, shifts)

Circularly shift, i.e. rotate, the data in src, storing the result in dest. shifts specifies the amount to shift in each dimension.

The dest array must be distinct from the src array (they cannot alias each other).

See also circshift.

source

Base.circcopy! — Function

  1. circcopy!(dest, src)

Copy src to dest, indexing each dimension modulo its length. src and dest must have the same size, but can be offset in their indices; any offset results in a (circular) wraparound. If the arrays have overlapping indices, then on the domain of the overlap dest agrees with src.

See also: circshift.

Examples

  1. julia> src = reshape(Vector(1:16), (4,4))
  2. 4×4 Array{Int64,2}:
  3. 1 5 9 13
  4. 2 6 10 14
  5. 3 7 11 15
  6. 4 8 12 16
  7. julia> dest = OffsetArray{Int}(undef, (0:3,2:5))
  8. julia> circcopy!(dest, src)
  9. OffsetArrays.OffsetArray{Int64,2,Array{Int64,2}} with indices 0:3×2:5:
  10. 8 12 16 4
  11. 5 9 13 1
  12. 6 10 14 2
  13. 7 11 15 3
  14. julia> dest[1:3,2:4] == src[1:3,2:4]
  15. true

source

Base.findall — Method

  1. findall(A)

Return a vector I of the true indices or keys of A. If there are no such elements of A, return an empty array. To search for other kinds of values, pass a predicate as the first argument.

Indices or keys are of the same type as those returned by keys(A) and pairs(A).

See also: findfirst, searchsorted.

Examples

  1. julia> A = [true, false, false, true]
  2. 4-element Vector{Bool}:
  3. 1
  4. 0
  5. 0
  6. 1
  7. julia> findall(A)
  8. 2-element Vector{Int64}:
  9. 1
  10. 4
  11. julia> A = [true false; false true]
  12. 2×2 Matrix{Bool}:
  13. 1 0
  14. 0 1
  15. julia> findall(A)
  16. 2-element Vector{CartesianIndex{2}}:
  17. CartesianIndex(1, 1)
  18. CartesianIndex(2, 2)
  19. julia> findall(falses(3))
  20. Int64[]

source

Base.findall — Method

  1. findall(f::Function, A)

Return a vector I of the indices or keys of A where f(A[I]) returns true. If there are no such elements of A, return an empty array.

Indices or keys are of the same type as those returned by keys(A) and pairs(A).

Examples

  1. julia> x = [1, 3, 4]
  2. 3-element Vector{Int64}:
  3. 1
  4. 3
  5. 4
  6. julia> findall(isodd, x)
  7. 2-element Vector{Int64}:
  8. 1
  9. 2
  10. julia> A = [1 2 0; 3 4 0]
  11. 2×3 Matrix{Int64}:
  12. 1 2 0
  13. 3 4 0
  14. julia> findall(isodd, A)
  15. 2-element Vector{CartesianIndex{2}}:
  16. CartesianIndex(1, 1)
  17. CartesianIndex(2, 1)
  18. julia> findall(!iszero, A)
  19. 4-element Vector{CartesianIndex{2}}:
  20. CartesianIndex(1, 1)
  21. CartesianIndex(2, 1)
  22. CartesianIndex(1, 2)
  23. CartesianIndex(2, 2)
  24. julia> d = Dict(:A => 10, :B => -1, :C => 0)
  25. Dict{Symbol, Int64} with 3 entries:
  26. :A => 10
  27. :B => -1
  28. :C => 0
  29. julia> findall(x -> x >= 0, d)
  30. 2-element Vector{Symbol}:
  31. :A
  32. :C

source

Base.findfirst — Method

  1. findfirst(A)

Return the index or key of the first true value in A. Return nothing if no such value is found. To search for other kinds of values, pass a predicate as the first argument.

Indices or keys are of the same type as those returned by keys(A) and pairs(A).

See also: findall, findnext, findlast, searchsortedfirst.

Examples

  1. julia> A = [false, false, true, false]
  2. 4-element Vector{Bool}:
  3. 0
  4. 0
  5. 1
  6. 0
  7. julia> findfirst(A)
  8. 3
  9. julia> findfirst(falses(3)) # returns nothing, but not printed in the REPL
  10. julia> A = [false false; true false]
  11. 2×2 Matrix{Bool}:
  12. 0 0
  13. 1 0
  14. julia> findfirst(A)
  15. CartesianIndex(2, 1)

source

Base.findfirst — Method

  1. findfirst(predicate::Function, A)

Return the index or key of the first element of A for which predicate returns true. Return nothing if there is no such element.

Indices or keys are of the same type as those returned by keys(A) and pairs(A).

Examples

  1. julia> A = [1, 4, 2, 2]
  2. 4-element Vector{Int64}:
  3. 1
  4. 4
  5. 2
  6. 2
  7. julia> findfirst(iseven, A)
  8. 2
  9. julia> findfirst(x -> x>10, A) # returns nothing, but not printed in the REPL
  10. julia> findfirst(isequal(4), A)
  11. 2
  12. julia> A = [1 4; 2 2]
  13. 2×2 Matrix{Int64}:
  14. 1 4
  15. 2 2
  16. julia> findfirst(iseven, A)
  17. CartesianIndex(2, 1)

source

Base.findlast — Method

  1. findlast(A)

Return the index or key of the last true value in A. Return nothing if there is no true value in A.

Indices or keys are of the same type as those returned by keys(A) and pairs(A).

See also: findfirst, findprev, findall.

Examples

  1. julia> A = [true, false, true, false]
  2. 4-element Vector{Bool}:
  3. 1
  4. 0
  5. 1
  6. 0
  7. julia> findlast(A)
  8. 3
  9. julia> A = falses(2,2);
  10. julia> findlast(A) # returns nothing, but not printed in the REPL
  11. julia> A = [true false; true false]
  12. 2×2 Matrix{Bool}:
  13. 1 0
  14. 1 0
  15. julia> findlast(A)
  16. CartesianIndex(2, 1)

source

Base.findlast — Method

  1. findlast(predicate::Function, A)

Return the index or key of the last element of A for which predicate returns true. Return nothing if there is no such element.

Indices or keys are of the same type as those returned by keys(A) and pairs(A).

Examples

  1. julia> A = [1, 2, 3, 4]
  2. 4-element Vector{Int64}:
  3. 1
  4. 2
  5. 3
  6. 4
  7. julia> findlast(isodd, A)
  8. 3
  9. julia> findlast(x -> x > 5, A) # returns nothing, but not printed in the REPL
  10. julia> A = [1 2; 3 4]
  11. 2×2 Matrix{Int64}:
  12. 1 2
  13. 3 4
  14. julia> findlast(isodd, A)
  15. CartesianIndex(2, 1)

source

Base.findnext — Method

  1. findnext(A, i)

Find the next index after or including i of a true element of A, or nothing if not found.

Indices are of the same type as those returned by keys(A) and pairs(A).

Examples

  1. julia> A = [false, false, true, false]
  2. 4-element Vector{Bool}:
  3. 0
  4. 0
  5. 1
  6. 0
  7. julia> findnext(A, 1)
  8. 3
  9. julia> findnext(A, 4) # returns nothing, but not printed in the REPL
  10. julia> A = [false false; true false]
  11. 2×2 Matrix{Bool}:
  12. 0 0
  13. 1 0
  14. julia> findnext(A, CartesianIndex(1, 1))
  15. CartesianIndex(2, 1)

source

Base.findnext — Method

  1. findnext(predicate::Function, A, i)

Find the next index after or including i of an element of A for which predicate returns true, or nothing if not found.

Indices are of the same type as those returned by keys(A) and pairs(A).

Examples

  1. julia> A = [1, 4, 2, 2];
  2. julia> findnext(isodd, A, 1)
  3. 1
  4. julia> findnext(isodd, A, 2) # returns nothing, but not printed in the REPL
  5. julia> A = [1 4; 2 2];
  6. julia> findnext(isodd, A, CartesianIndex(1, 1))
  7. CartesianIndex(1, 1)

source

Base.findprev — Method

  1. findprev(A, i)

Find the previous index before or including i of a true element of A, or nothing if not found.

Indices are of the same type as those returned by keys(A) and pairs(A).

See also: findnext, findfirst, findall.

Examples

  1. julia> A = [false, false, true, true]
  2. 4-element Vector{Bool}:
  3. 0
  4. 0
  5. 1
  6. 1
  7. julia> findprev(A, 3)
  8. 3
  9. julia> findprev(A, 1) # returns nothing, but not printed in the REPL
  10. julia> A = [false false; true true]
  11. 2×2 Matrix{Bool}:
  12. 0 0
  13. 1 1
  14. julia> findprev(A, CartesianIndex(2, 1))
  15. CartesianIndex(2, 1)

source

Base.findprev — Method

  1. findprev(predicate::Function, A, i)

Find the previous index before or including i of an element of A for which predicate returns true, or nothing if not found.

Indices are of the same type as those returned by keys(A) and pairs(A).

Examples

  1. julia> A = [4, 6, 1, 2]
  2. 4-element Vector{Int64}:
  3. 4
  4. 6
  5. 1
  6. 2
  7. julia> findprev(isodd, A, 1) # returns nothing, but not printed in the REPL
  8. julia> findprev(isodd, A, 3)
  9. 3
  10. julia> A = [4 6; 1 2]
  11. 2×2 Matrix{Int64}:
  12. 4 6
  13. 1 2
  14. julia> findprev(isodd, A, CartesianIndex(1, 2))
  15. CartesianIndex(2, 1)

source

Base.permutedims — Function

  1. permutedims(A::AbstractArray, perm)

Permute the dimensions of array A. perm is a vector or a tuple of length ndims(A) specifying the permutation.

See also permutedims!, PermutedDimsArray, transpose, invperm.

Examples

  1. julia> A = reshape(Vector(1:8), (2,2,2))
  2. 2×2×2 Array{Int64, 3}:
  3. [:, :, 1] =
  4. 1 3
  5. 2 4
  6. [:, :, 2] =
  7. 5 7
  8. 6 8
  9. julia> perm = (3, 1, 2); # put the last dimension first
  10. julia> B = permutedims(A, perm)
  11. 2×2×2 Array{Int64, 3}:
  12. [:, :, 1] =
  13. 1 2
  14. 5 6
  15. [:, :, 2] =
  16. 3 4
  17. 7 8
  18. julia> A == permutedims(B, invperm(perm)) # the inverse permutation
  19. true

For each dimension i of B = permutedims(A, perm), its corresponding dimension of A will be perm[i]. This means the equality size(B, i) == size(A, perm[i]) holds.

  1. julia> A = randn(5, 7, 11, 13);
  2. julia> perm = [4, 1, 3, 2];
  3. julia> B = permutedims(A, perm);
  4. julia> size(B)
  5. (13, 5, 11, 7)
  6. julia> size(A)[perm] == ans
  7. true

source

  1. permutedims(m::AbstractMatrix)

Permute the dimensions of the matrix m, by flipping the elements across the diagonal of the matrix. Differs from LinearAlgebra‘s transpose in that the operation is not recursive.

Examples

  1. julia> a = [1 2; 3 4];
  2. julia> b = [5 6; 7 8];
  3. julia> c = [9 10; 11 12];
  4. julia> d = [13 14; 15 16];
  5. julia> X = [[a] [b]; [c] [d]]
  6. 2×2 Matrix{Matrix{Int64}}:
  7. [1 2; 3 4] [5 6; 7 8]
  8. [9 10; 11 12] [13 14; 15 16]
  9. julia> permutedims(X)
  10. 2×2 Matrix{Matrix{Int64}}:
  11. [1 2; 3 4] [9 10; 11 12]
  12. [5 6; 7 8] [13 14; 15 16]
  13. julia> transpose(X)
  14. 2×2 transpose(::Matrix{Matrix{Int64}}) with eltype Transpose{Int64, Matrix{Int64}}:
  15. [1 3; 2 4] [9 11; 10 12]
  16. [5 7; 6 8] [13 15; 14 16]

source

  1. permutedims(v::AbstractVector)

Reshape vector v into a 1 × length(v) row matrix. Differs from LinearAlgebra‘s transpose in that the operation is not recursive.

Examples

  1. julia> permutedims([1, 2, 3, 4])
  2. 1×4 Matrix{Int64}:
  3. 1 2 3 4
  4. julia> V = [[[1 2; 3 4]]; [[5 6; 7 8]]]
  5. 2-element Vector{Matrix{Int64}}:
  6. [1 2; 3 4]
  7. [5 6; 7 8]
  8. julia> permutedims(V)
  9. 1×2 Matrix{Matrix{Int64}}:
  10. [1 2; 3 4] [5 6; 7 8]
  11. julia> transpose(V)
  12. 1×2 transpose(::Vector{Matrix{Int64}}) with eltype Transpose{Int64, Matrix{Int64}}:
  13. [1 3; 2 4] [5 7; 6 8]

source

Base.permutedims! — Function

  1. permutedims!(dest, src, perm)

Permute the dimensions of array src and store the result in the array dest. perm is a vector specifying a permutation of length ndims(src). The preallocated array dest should have size(dest) == size(src)[perm] and is completely overwritten. No in-place permutation is supported and unexpected results will happen if src and dest have overlapping memory regions.

See also permutedims.

source

Base.PermutedDimsArrays.PermutedDimsArray — Type

  1. PermutedDimsArray(A, perm) -> B

Given an AbstractArray A, create a view B such that the dimensions appear to be permuted. Similar to permutedims, except that no copying occurs (B shares storage with A).

See also permutedims, invperm.

Examples

  1. julia> A = rand(3,5,4);
  2. julia> B = PermutedDimsArray(A, (3,1,2));
  3. julia> size(B)
  4. (4, 3, 5)
  5. julia> B[3,1,2] == A[1,2,3]
  6. true

source

Base.promote_shape — Function

  1. promote_shape(s1, s2)

Check two array shapes for compatibility, allowing trailing singleton dimensions, and return whichever shape has more dimensions.

Examples

  1. julia> a = fill(1, (3,4,1,1,1));
  2. julia> b = fill(1, (3,4));
  3. julia> promote_shape(a,b)
  4. (Base.OneTo(3), Base.OneTo(4), Base.OneTo(1), Base.OneTo(1), Base.OneTo(1))
  5. julia> promote_shape((2,3,1,4), (2, 3, 1, 4, 1))
  6. (2, 3, 1, 4, 1)

source

Array functions

Base.accumulate — Function

  1. accumulate(op, A; dims::Integer, [init])

Cumulative operation op along the dimension dims of A (providing dims is optional for vectors). An initial value init may optionally be provided by a keyword argument. See also accumulate! to use a preallocated output array, both for performance and to control the precision of the output (e.g. to avoid overflow).

For common operations there are specialized variants of accumulate, see cumsum, cumprod. For a lazy version, see Iterators.accumulate.

Julia 1.5

accumulate on a non-array iterator requires at least Julia 1.5.

Examples

  1. julia> accumulate(+, [1,2,3])
  2. 3-element Vector{Int64}:
  3. 1
  4. 3
  5. 6
  6. julia> accumulate(min, (1, -2, 3, -4, 5), init=0)
  7. (0, -2, -2, -4, -4)
  8. julia> accumulate(/, (2, 4, Inf), init=100)
  9. (50.0, 12.5, 0.0)
  10. julia> accumulate(=>, i^2 for i in 1:3)
  11. 3-element Vector{Any}:
  12. 1
  13. 1 => 4
  14. (1 => 4) => 9
  15. julia> accumulate(+, fill(1, 3, 4))
  16. 3×4 Matrix{Int64}:
  17. 1 4 7 10
  18. 2 5 8 11
  19. 3 6 9 12
  20. julia> accumulate(+, fill(1, 2, 5), dims=2, init=100.0)
  21. 2×5 Matrix{Float64}:
  22. 101.0 102.0 103.0 104.0 105.0
  23. 101.0 102.0 103.0 104.0 105.0

source

Base.accumulate! — Function

  1. accumulate!(op, B, A; [dims], [init])

Cumulative operation op on A along the dimension dims, storing the result in B. Providing dims is optional for vectors. If the keyword argument init is given, its value is used to instantiate the accumulation.

See also accumulate, cumsum!, cumprod!.

Examples

  1. julia> x = [1, 0, 2, 0, 3];
  2. julia> y = rand(5);
  3. julia> accumulate!(+, y, x);
  4. julia> y
  5. 5-element Vector{Float64}:
  6. 1.0
  7. 1.0
  8. 3.0
  9. 3.0
  10. 6.0
  11. julia> A = [1 2 3; 4 5 6];
  12. julia> B = similar(A);
  13. julia> accumulate!(-, B, A, dims=1)
  14. 2×3 Matrix{Int64}:
  15. 1 2 3
  16. -3 -3 -3
  17. julia> accumulate!(*, B, A, dims=2, init=10)
  18. 2×3 Matrix{Int64}:
  19. 10 20 60
  20. 40 200 1200

source

Base.cumprod — Function

  1. cumprod(A; dims::Integer)

Cumulative product along the dimension dim. See also cumprod! to use a preallocated output array, both for performance and to control the precision of the output (e.g. to avoid overflow).

Examples

  1. julia> a = Int8[1 2 3; 4 5 6];
  2. julia> cumprod(a, dims=1)
  3. 2×3 Matrix{Int64}:
  4. 1 2 3
  5. 4 10 18
  6. julia> cumprod(a, dims=2)
  7. 2×3 Matrix{Int64}:
  8. 1 2 6
  9. 4 20 120

source

  1. cumprod(itr)

Cumulative product of an iterator.

See also cumprod!, accumulate, cumsum.

Julia 1.5

cumprod on a non-array iterator requires at least Julia 1.5.

Examples

  1. julia> cumprod(fill(1//2, 3))
  2. 3-element Vector{Rational{Int64}}:
  3. 1//2
  4. 1//4
  5. 1//8
  6. julia> cumprod((1, 2, 1, 3, 1))
  7. (1, 2, 2, 6, 6)
  8. julia> cumprod("julia")
  9. 5-element Vector{String}:
  10. "j"
  11. "ju"
  12. "jul"
  13. "juli"
  14. "julia"

source

Base.cumprod! — Function

  1. cumprod!(B, A; dims::Integer)

Cumulative product of A along the dimension dims, storing the result in B. See also cumprod.

source

  1. cumprod!(y::AbstractVector, x::AbstractVector)

Cumulative product of a vector x, storing the result in y. See also cumprod.

source

Base.cumsum — Function

  1. cumsum(A; dims::Integer)

Cumulative sum along the dimension dims. See also cumsum! to use a preallocated output array, both for performance and to control the precision of the output (e.g. to avoid overflow).

Examples

  1. julia> a = [1 2 3; 4 5 6]
  2. 2×3 Matrix{Int64}:
  3. 1 2 3
  4. 4 5 6
  5. julia> cumsum(a, dims=1)
  6. 2×3 Matrix{Int64}:
  7. 1 2 3
  8. 5 7 9
  9. julia> cumsum(a, dims=2)
  10. 2×3 Matrix{Int64}:
  11. 1 3 6
  12. 4 9 15

Note

The return array’s eltype is Int for signed integers of less than system word size and UInt for unsigned integers of less than system word size. To preserve eltype of arrays with small signed or unsigned integer accumulate(+, A) should be used.

  1. julia> cumsum(Int8[100, 28])
  2. 2-element Vector{Int64}:
  3. 100
  4. 128
  5. julia> accumulate(+,Int8[100, 28])
  6. 2-element Vector{Int8}:
  7. 100
  8. -128

In the former case, the integers are widened to system word size and therefore the result is Int64[100, 128]. In the latter case, no such widening happens and integer overflow results in Int8[100, -128].

source

  1. cumsum(itr)

Cumulative sum of an iterator.

See also accumulate to apply functions other than +.

Julia 1.5

cumsum on a non-array iterator requires at least Julia 1.5.

Examples

  1. julia> cumsum(1:3)
  2. 3-element Vector{Int64}:
  3. 1
  4. 3
  5. 6
  6. julia> cumsum((true, false, true, false, true))
  7. (1, 1, 2, 2, 3)
  8. julia> cumsum(fill(1, 2) for i in 1:3)
  9. 3-element Vector{Vector{Int64}}:
  10. [1, 1]
  11. [2, 2]
  12. [3, 3]

source

Base.cumsum! — Function

  1. cumsum!(B, A; dims::Integer)

Cumulative sum of A along the dimension dims, storing the result in B. See also cumsum.

source

Base.diff — Function

  1. diff(A::AbstractVector)
  2. diff(A::AbstractArray; dims::Integer)

Finite difference operator on a vector or a multidimensional array A. In the latter case the dimension to operate on needs to be specified with the dims keyword argument.

Julia 1.1

diff for arrays with dimension higher than 2 requires at least Julia 1.1.

Examples

  1. julia> a = [2 4; 6 16]
  2. 2×2 Matrix{Int64}:
  3. 2 4
  4. 6 16
  5. julia> diff(a, dims=2)
  6. 2×1 Matrix{Int64}:
  7. 2
  8. 10
  9. julia> diff(vec(a))
  10. 3-element Vector{Int64}:
  11. 4
  12. -2
  13. 12

source

Base.repeat — Function

  1. repeat(A::AbstractArray, counts::Integer...)

Construct an array by repeating array A a given number of times in each dimension, specified by counts.

See also: fill, Iterators.repeated, Iterators.cycle.

Examples

  1. julia> repeat([1, 2, 3], 2)
  2. 6-element Vector{Int64}:
  3. 1
  4. 2
  5. 3
  6. 1
  7. 2
  8. 3
  9. julia> repeat([1, 2, 3], 2, 3)
  10. 6×3 Matrix{Int64}:
  11. 1 1 1
  12. 2 2 2
  13. 3 3 3
  14. 1 1 1
  15. 2 2 2
  16. 3 3 3

source

  1. repeat(A::AbstractArray; inner=ntuple(Returns(1), ndims(A)), outer=ntuple(Returns(1), ndims(A)))

Construct an array by repeating the entries of A. The i-th element of inner specifies the number of times that the individual entries of the i-th dimension of A should be repeated. The i-th element of outer specifies the number of times that a slice along the i-th dimension of A should be repeated. If inner or outer are omitted, no repetition is performed.

Examples

  1. julia> repeat(1:2, inner=2)
  2. 4-element Vector{Int64}:
  3. 1
  4. 1
  5. 2
  6. 2
  7. julia> repeat(1:2, outer=2)
  8. 4-element Vector{Int64}:
  9. 1
  10. 2
  11. 1
  12. 2
  13. julia> repeat([1 2; 3 4], inner=(2, 1), outer=(1, 3))
  14. 4×6 Matrix{Int64}:
  15. 1 2 1 2 1 2
  16. 1 2 1 2 1 2
  17. 3 4 3 4 3 4
  18. 3 4 3 4 3 4

source

  1. repeat(s::AbstractString, r::Integer)

Repeat a string r times. This can be written as s^r.

See also ^.

Examples

  1. julia> repeat("ha", 3)
  2. "hahaha"

source

  1. repeat(c::AbstractChar, r::Integer) -> String

Repeat a character r times. This can equivalently be accomplished by calling c^r.

Examples

  1. julia> repeat('A', 3)
  2. "AAA"

source

Base.rot180 — Function

  1. rot180(A)

Rotate matrix A 180 degrees.

Examples

  1. julia> a = [1 2; 3 4]
  2. 2×2 Matrix{Int64}:
  3. 1 2
  4. 3 4
  5. julia> rot180(a)
  6. 2×2 Matrix{Int64}:
  7. 4 3
  8. 2 1

source

  1. rot180(A, k)

Rotate matrix A 180 degrees an integer k number of times. If k is even, this is equivalent to a copy.

Examples

  1. julia> a = [1 2; 3 4]
  2. 2×2 Matrix{Int64}:
  3. 1 2
  4. 3 4
  5. julia> rot180(a,1)
  6. 2×2 Matrix{Int64}:
  7. 4 3
  8. 2 1
  9. julia> rot180(a,2)
  10. 2×2 Matrix{Int64}:
  11. 1 2
  12. 3 4

source

Base.rotl90 — Function

  1. rotl90(A)

Rotate matrix A left 90 degrees.

Examples

  1. julia> a = [1 2; 3 4]
  2. 2×2 Matrix{Int64}:
  3. 1 2
  4. 3 4
  5. julia> rotl90(a)
  6. 2×2 Matrix{Int64}:
  7. 2 4
  8. 1 3

source

  1. rotl90(A, k)

Left-rotate matrix A 90 degrees counterclockwise an integer k number of times. If k is a multiple of four (including zero), this is equivalent to a copy.

Examples

  1. julia> a = [1 2; 3 4]
  2. 2×2 Matrix{Int64}:
  3. 1 2
  4. 3 4
  5. julia> rotl90(a,1)
  6. 2×2 Matrix{Int64}:
  7. 2 4
  8. 1 3
  9. julia> rotl90(a,2)
  10. 2×2 Matrix{Int64}:
  11. 4 3
  12. 2 1
  13. julia> rotl90(a,3)
  14. 2×2 Matrix{Int64}:
  15. 3 1
  16. 4 2
  17. julia> rotl90(a,4)
  18. 2×2 Matrix{Int64}:
  19. 1 2
  20. 3 4

source

Base.rotr90 — Function

  1. rotr90(A)

Rotate matrix A right 90 degrees.

Examples

  1. julia> a = [1 2; 3 4]
  2. 2×2 Matrix{Int64}:
  3. 1 2
  4. 3 4
  5. julia> rotr90(a)
  6. 2×2 Matrix{Int64}:
  7. 3 1
  8. 4 2

source

  1. rotr90(A, k)

Right-rotate matrix A 90 degrees clockwise an integer k number of times. If k is a multiple of four (including zero), this is equivalent to a copy.

Examples

  1. julia> a = [1 2; 3 4]
  2. 2×2 Matrix{Int64}:
  3. 1 2
  4. 3 4
  5. julia> rotr90(a,1)
  6. 2×2 Matrix{Int64}:
  7. 3 1
  8. 4 2
  9. julia> rotr90(a,2)
  10. 2×2 Matrix{Int64}:
  11. 4 3
  12. 2 1
  13. julia> rotr90(a,3)
  14. 2×2 Matrix{Int64}:
  15. 2 4
  16. 1 3
  17. julia> rotr90(a,4)
  18. 2×2 Matrix{Int64}:
  19. 1 2
  20. 3 4

source

Base.mapslices — Function

  1. mapslices(f, A; dims)

Transform the given dimensions of array A by applying a function f on each slice of the form A[..., :, ..., :, ...], with a colon at each d in dims. The results are concatenated along the remaining dimensions.

For example, if dims = [1,2] and A is 4-dimensional, then f is called on x = A[:,:,i,j] for all i and j, and f(x) becomes R[:,:,i,j] in the result R.

See also eachcol or eachslice, used with map or stack.

Examples

  1. julia> A = reshape(1:30,(2,5,3))
  2. 2×5×3 reshape(::UnitRange{Int64}, 2, 5, 3) with eltype Int64:
  3. [:, :, 1] =
  4. 1 3 5 7 9
  5. 2 4 6 8 10
  6. [:, :, 2] =
  7. 11 13 15 17 19
  8. 12 14 16 18 20
  9. [:, :, 3] =
  10. 21 23 25 27 29
  11. 22 24 26 28 30
  12. julia> f(x::Matrix) = fill(x[1,1], 1,4); # returns a 1×4 matrix
  13. julia> B = mapslices(f, A, dims=(1,2))
  14. 1×4×3 Array{Int64, 3}:
  15. [:, :, 1] =
  16. 1 1 1 1
  17. [:, :, 2] =
  18. 11 11 11 11
  19. [:, :, 3] =
  20. 21 21 21 21
  21. julia> f2(x::AbstractMatrix) = fill(x[1,1], 1,4);
  22. julia> B == stack(f2, eachslice(A, dims=3))
  23. true
  24. julia> g(x) = x[begin] // x[end-1]; # returns a number
  25. julia> mapslices(g, A, dims=[1,3])
  26. 1×5×1 Array{Rational{Int64}, 3}:
  27. [:, :, 1] =
  28. 1//21 3//23 1//5 7//27 9//29
  29. julia> map(g, eachslice(A, dims=2))
  30. 5-element Vector{Rational{Int64}}:
  31. 1//21
  32. 3//23
  33. 1//5
  34. 7//27
  35. 9//29
  36. julia> mapslices(sum, A; dims=(1,3)) == sum(A; dims=(1,3))
  37. true

Notice that in eachslice(A; dims=2), the specified dimension is the one without a colon in the slice. This is view(A,:,i,:), whereas mapslices(f, A; dims=(1,3)) uses A[:,i,:]. The function f may mutate values in the slice without affecting A.

source

Base.eachrow — Function

  1. eachrow(A::AbstractVecOrMat) <: AbstractVector

Create a RowSlices object that is a vector of rows of matrix or vector A. Row slices are returned as AbstractVector views of A.

For the inverse, see stack(rows; dims=1).

See also eachcol, eachslice and mapslices.

Julia 1.1

This function requires at least Julia 1.1.

Julia 1.9

Prior to Julia 1.9, this returned an iterator.

Example

  1. julia> a = [1 2; 3 4]
  2. 2×2 Matrix{Int64}:
  3. 1 2
  4. 3 4
  5. julia> s = eachrow(a)
  6. 2-element RowSlices{Matrix{Int64}, Tuple{Base.OneTo{Int64}}, SubArray{Int64, 1, Matrix{Int64}, Tuple{Int64, Base.Slice{Base.OneTo{Int64}}}, true}}:
  7. [1, 2]
  8. [3, 4]
  9. julia> s[1]
  10. 2-element view(::Matrix{Int64}, 1, :) with eltype Int64:
  11. 1
  12. 2

source

Base.eachcol — Function

  1. eachcol(A::AbstractVecOrMat) <: AbstractVector

Create a ColumnSlices object that is a vector of columns of matrix or vector A. Column slices are returned as AbstractVector views of A.

For the inverse, see stack(cols) or reduce(hcat, cols).

See also eachrow, eachslice and mapslices.

Julia 1.1

This function requires at least Julia 1.1.

Julia 1.9

Prior to Julia 1.9, this returned an iterator.

Example

  1. julia> a = [1 2; 3 4]
  2. 2×2 Matrix{Int64}:
  3. 1 2
  4. 3 4
  5. julia> s = eachcol(a)
  6. 2-element ColumnSlices{Matrix{Int64}, Tuple{Base.OneTo{Int64}}, SubArray{Int64, 1, Matrix{Int64}, Tuple{Base.Slice{Base.OneTo{Int64}}, Int64}, true}}:
  7. [1, 3]
  8. [2, 4]
  9. julia> s[1]
  10. 2-element view(::Matrix{Int64}, :, 1) with eltype Int64:
  11. 1
  12. 3

source

Base.eachslice — Function

  1. eachslice(A::AbstractArray; dims, drop=true)

Create a Slices object that is an array of slices over dimensions dims of A, returning views that select all the data from the other dimensions in A. dims can either by an integer or a tuple of integers.

If drop = true (the default), the outer Slices will drop the inner dimensions, and the ordering of the dimensions will match those in dims. If drop = false, then the Slices will have the same dimensionality as the underlying array, with inner dimensions having size 1.

See stack(slices; dims) for the inverse of eachslice(A; dims::Integer).

See also eachrow, eachcol, mapslices and selectdim.

Julia 1.1

This function requires at least Julia 1.1.

Julia 1.9

Prior to Julia 1.9, this returned an iterator, and only a single dimension dims was supported.

Example

  1. julia> m = [1 2 3; 4 5 6; 7 8 9]
  2. 3×3 Matrix{Int64}:
  3. 1 2 3
  4. 4 5 6
  5. 7 8 9
  6. julia> s = eachslice(m, dims=1)
  7. 3-element RowSlices{Matrix{Int64}, Tuple{Base.OneTo{Int64}}, SubArray{Int64, 1, Matrix{Int64}, Tuple{Int64, Base.Slice{Base.OneTo{Int64}}}, true}}:
  8. [1, 2, 3]
  9. [4, 5, 6]
  10. [7, 8, 9]
  11. julia> s[1]
  12. 3-element view(::Matrix{Int64}, 1, :) with eltype Int64:
  13. 1
  14. 2
  15. 3
  16. julia> eachslice(m, dims=1, drop=false)
  17. 3×1 Slices{Matrix{Int64}, Tuple{Int64, Colon}, Tuple{Base.OneTo{Int64}, Base.OneTo{Int64}}, SubArray{Int64, 1, Matrix{Int64}, Tuple{Int64, Base.Slice{Base.OneTo{Int64}}}, true}, 2}:
  18. [1, 2, 3]
  19. [4, 5, 6]
  20. [7, 8, 9]

source

Combinatorics

Base.invperm — Function

  1. invperm(v)

Return the inverse permutation of v. If B = A[v], then A == B[invperm(v)].

See also sortperm, invpermute!, isperm, permutedims.

Examples

  1. julia> p = (2, 3, 1);
  2. julia> invperm(p)
  3. (3, 1, 2)
  4. julia> v = [2; 4; 3; 1];
  5. julia> invperm(v)
  6. 4-element Vector{Int64}:
  7. 4
  8. 1
  9. 3
  10. 2
  11. julia> A = ['a','b','c','d'];
  12. julia> B = A[v]
  13. 4-element Vector{Char}:
  14. 'b': ASCII/Unicode U+0062 (category Ll: Letter, lowercase)
  15. 'd': ASCII/Unicode U+0064 (category Ll: Letter, lowercase)
  16. 'c': ASCII/Unicode U+0063 (category Ll: Letter, lowercase)
  17. 'a': ASCII/Unicode U+0061 (category Ll: Letter, lowercase)
  18. julia> B[invperm(v)]
  19. 4-element Vector{Char}:
  20. 'a': ASCII/Unicode U+0061 (category Ll: Letter, lowercase)
  21. 'b': ASCII/Unicode U+0062 (category Ll: Letter, lowercase)
  22. 'c': ASCII/Unicode U+0063 (category Ll: Letter, lowercase)
  23. 'd': ASCII/Unicode U+0064 (category Ll: Letter, lowercase)

source

Base.isperm — Function

  1. isperm(v) -> Bool

Return true if v is a valid permutation.

Examples

  1. julia> isperm([1; 2])
  2. true
  3. julia> isperm([1; 3])
  4. false

source

Base.permute! — Method

  1. permute!(v, p)

Permute vector v in-place, according to permutation p. No checking is done to verify that p is a permutation.

To return a new permutation, use v[p]. Note that this is faster than permute!(v, p).

See also invpermute!.

Examples

  1. julia> A = [1, 1, 3, 4];
  2. julia> perm = [2, 4, 3, 1];
  3. julia> permute!(A, perm);
  4. julia> A
  5. 4-element Vector{Int64}:
  6. 1
  7. 4
  8. 3
  9. 1

source

Base.invpermute! — Function

  1. invpermute!(v, p)

Like permute!, but the inverse of the given permutation is applied.

Examples

  1. julia> A = [1, 1, 3, 4];
  2. julia> perm = [2, 4, 3, 1];
  3. julia> invpermute!(A, perm);
  4. julia> A
  5. 4-element Vector{Int64}:
  6. 4
  7. 1
  8. 3
  9. 1

source

Base.reverse — Method

  1. reverse(A; dims=:)

Reverse A along dimension dims, which can be an integer (a single dimension), a tuple of integers (a tuple of dimensions) or : (reverse along all the dimensions, the default). See also reverse! for in-place reversal.

Examples

  1. julia> b = Int64[1 2; 3 4]
  2. 2×2 Matrix{Int64}:
  3. 1 2
  4. 3 4
  5. julia> reverse(b, dims=2)
  6. 2×2 Matrix{Int64}:
  7. 2 1
  8. 4 3
  9. julia> reverse(b)
  10. 2×2 Matrix{Int64}:
  11. 4 3
  12. 2 1

Julia 1.6

Prior to Julia 1.6, only single-integer dims are supported in reverse.

source

Base.reverseind — Function

  1. reverseind(v, i)

Given an index i in reverse(v), return the corresponding index in v so that v[reverseind(v,i)] == reverse(v)[i]. (This can be nontrivial in cases where v contains non-ASCII characters.)

Examples

  1. julia> s = "Julia🚀"
  2. "Julia🚀"
  3. julia> r = reverse(s)
  4. "🚀ailuJ"
  5. julia> for i in eachindex(s)
  6. print(r[reverseind(r, i)])
  7. end
  8. Julia🚀

source

Base.reverse! — Function

  1. reverse!(v [, start=firstindex(v) [, stop=lastindex(v) ]]) -> v

In-place version of reverse.

Examples

  1. julia> A = Vector(1:5)
  2. 5-element Vector{Int64}:
  3. 1
  4. 2
  5. 3
  6. 4
  7. 5
  8. julia> reverse!(A);
  9. julia> A
  10. 5-element Vector{Int64}:
  11. 5
  12. 4
  13. 3
  14. 2
  15. 1

source

  1. reverse!(A; dims=:)

Like reverse, but operates in-place in A.

Julia 1.6

Multidimensional reverse! requires Julia 1.6.

source