Arrays

Arrays

Constructors and Types

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.

source
AbstractVector{T}

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

source
AbstractMatrix{T}

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

source
Core.ArrayType.
Array{T,N} <: AbstractArray{T,N}

N-dimensional dense array with elements of type T.

source
Core.ArrayMethod.
Array{T}(uninitialized, dims)
Array{T,N}(uninitialized, dims)

Construct an uninitialized N-dimensional Array containing elements of type T. N can either be supplied explicitly, as in Array{T,N}(uninitialized, 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. See uninitialized.

Examples

julia> A = Array{Float64,2}(uninitialized, 2, 3) # N given explicitly
2×3 Array{Float64,2}:
 6.90198e-310  6.90198e-310  6.90198e-310
 6.90198e-310  6.90198e-310  0.0

julia> B = Array{Float64}(uninitialized, 2) # N determined by the input
2-element Array{Float64,1}:
 1.87103e-320
 0.0
source
Core.ArrayMethod.
Array{T}(nothing, dims)
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

julia> Array{Union{Nothing, String}}(nothing, 2)
2-element Array{Union{Nothing, String},1}:
 nothing
 nothing

julia> Array{Union{Nothing, Int}}(nothing, 2, 3)
2×3 Array{Union{Nothing, Int64},2}:
 nothing  nothing  nothing
 nothing  nothing  nothing
source
Core.ArrayMethod.
Array{T}(missing, dims)
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

julia> Array{Union{Missing, String}}(missing, 2)
2-element Array{Union{Missing, String},1}:
 missing
 missing

julia> Array{Union{Missing, Int}}(missing, 2, 3)
2×3 Array{Union{Missing, Int64},2}:
 missing  missing  missing
 missing  missing  missing
source
Uninitialized

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

Examples

julia> Array{Float64,1}(Uninitialized(), 3)
3-element Array{Float64,1}:
 2.2752528595e-314
 2.202942107e-314
 2.275252907e-314
source
Core.uninitializedConstant.
uninitialized

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

Examples

julia> Array{Float64,1}(uninitialized, 3)
3-element Array{Float64,1}:
 2.2752528595e-314
 2.202942107e-314
 2.275252907e-314
source
Base.VectorType.
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}.

source
Base.VectorMethod.
Vector{T}(uninitialized, n)

Construct an uninitialized Vector{T} of length n. See uninitialized.

Examples

julia> Vector{Float64}(uninitialized, 3)
3-element Array{Float64,1}:
 6.90966e-310
 6.90966e-310
 6.90966e-310
source
Base.VectorMethod.
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

julia> Vector{Union{Nothing, String}}(nothing, 2)
2-element Array{Union{Nothing, String},1}:
 nothing
 nothing
source
Base.VectorMethod.
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

julia> Vector{Union{Missing, String}}(missing, 2)
2-element Array{Union{Missing, String},1}:
 missing
 missing
source
Base.MatrixType.
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}.

source
Base.MatrixMethod.
Matrix{T}(uninitialized, m, n)

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

Examples

julia> Matrix{Float64}(uninitialized, 2, 3)
2×3 Array{Float64,2}:
 6.93517e-310  6.93517e-310  6.93517e-310
 6.93517e-310  6.93517e-310  1.29396e-320
source
Base.MatrixMethod.
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

julia> Matrix{Union{Nothing, String}}(nothing, 2, 3)
2×3 Array{Union{Nothing, String},2}:
 nothing  nothing  nothing
 nothing  nothing  nothing
source
Base.MatrixMethod.
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

julia> Matrix{Union{Missing, String}}(missing, 2, 3)
2×3 Array{Union{Missing, String},2}:
 missing  missing  missing
 missing  missing  missing
source
Base.getindexMethod.
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

julia> Int8[1, 2, 3]
3-element Array{Int8,1}:
 1
 2
 3

julia> getindex(Int8, 1, 2, 3)
3-element Array{Int8,1}:
 1
 2
 3
source
Base.zerosFunction.
zeros([T=Float64,] dims...)

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

Examples

julia> zeros(1)
1-element Array{Float64,1}:
 0.0

julia> zeros(Int8, 2, 3)
2×3 Array{Int8,2}:
 0  0  0
 0  0  0
source
Base.onesFunction.
ones([T=Float64,] dims...)

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

Examples

julia> ones(1,2)
1×2 Array{Float64,2}:
 1.0  1.0

julia> ones(ComplexF64, 2, 3)
2×3 Array{Complex{Float64},2}:
 1.0+0.0im  1.0+0.0im  1.0+0.0im
 1.0+0.0im  1.0+0.0im  1.0+0.0im
source
Base.BitArrayType.
BitArray{N} <: DenseArray{Bool, N}

Space-efficient N-dimensional boolean array, which stores one bit per boolean value.

source
Base.BitArrayMethod.
BitArray(uninitialized, dims::Integer...)
BitArray{N}(uninitialized, dims::NTuple{N,Int})

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

Examples

julia> BitArray(uninitialized, 2, 2)
2×2 BitArray{2}:
 false  false
 false  true

julia> BitArray(uninitialized, (3, 1))
3×1 BitArray{2}:
 false
 true
 false
source
Base.BitArrayMethod.
BitArray(itr)

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

Examples

julia> BitArray([1 0; 0 1])
2×2 BitArray{2}:
  true  false
 false   true

julia> BitArray(x+y == 3 for x = 1:2, y = 1:3)
2×3 BitArray{2}:
 false   true  false
  true  false  false

julia> BitArray(x+y == 3 for x = 1:2 for y = 1:3)
6-element BitArray{1}:
 false
  true
 false
  true
 false
 false
source
Base.truesFunction.
trues(dims)

Create a BitArray with all values set to true.

Examples

julia> trues(2,3)
2×3 BitArray{2}:
 true  true  true
 true  true  true
source
Base.falsesFunction.
falses(dims)

Create a BitArray with all values set to false.

Examples

julia> falses(2,3)
2×3 BitArray{2}:
 false  false  false
 false  false  false
source
Base.fillFunction.
fill(x, dims)

Create an array filled with the value x. For example, fill(1.0, (5,5)) returns a 5×5 array of floats, with each element initialized to 1.0.

Examples

julia> fill(1.0, (5,5))
5×5 Array{Float64,2}:
 1.0  1.0  1.0  1.0  1.0
 1.0  1.0  1.0  1.0  1.0
 1.0  1.0  1.0  1.0  1.0
 1.0  1.0  1.0  1.0  1.0
 1.0  1.0  1.0  1.0  1.0

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

source
Base.fill!Function.
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

julia> A = zeros(2,3)
2×3 Array{Float64,2}:
 0.0  0.0  0.0
 0.0  0.0  0.0

julia> fill!(A, 2.)
2×3 Array{Float64,2}:
 2.0  2.0  2.0
 2.0  2.0  2.0

julia> a = [1, 1, 1]; A = fill!(Vector{Vector{Int}}(uninitialized, 3), a); a[1] = 2; A
3-element Array{Array{Int64,1},1}:
 [2, 1, 1]
 [2, 1, 1]
 [2, 1, 1]

julia> x = 0; f() = (global x += 1; x); fill!(Vector{Int}(uninitialized, 3), f())
3-element Array{Int64,1}:
 1
 1
 1
source
Base.similarMethod.
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}(uninitialized, dims...).

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

julia> similar(1:10, 1, 4)
1×4 Array{Int64,2}:
 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:

julia> similar(trues(10,10), 2)
2-element BitArray{1}:
 false
 false

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

julia> similar(falses(10), Float64, 2, 4)
2×4 Array{Float64,2}:
 2.18425e-314  2.18425e-314  2.18425e-314  2.18425e-314
 2.18425e-314  2.18425e-314  2.18425e-314  2.18425e-314
source
Base.similarMethod.
similar(storagetype, indices)

Create an uninitialized mutable array analogous to that specified by storagetype, but with indices specified by the last argument. storagetype might be a type or a function.

Examples:

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}(uninitialized, size(A)), but if A has unconventional indexing then the indices of the result will match A.

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

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

similar(dims->zeros(Int, dims), axes(A))

would create an array of Int, initialized to zero, matching the indices of A.

source

Basic functions

Base.ndimsFunction.
ndims(A::AbstractArray) -> Integer

Return the number of dimensions of A.

Examples

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

julia> ndims(A)
3
source
Base.sizeFunction.
size(A::AbstractArray, [dim...])

Return a tuple containing the dimensions of A. Optionally you can specify the dimension(s) you want the length of, and get the length of that dimension, or a tuple of the lengths of dimensions you asked for.

Examples

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

julia> size(A, 2)
3

julia> size(A, 3, 2)
(4, 3)
source
Base.axesMethod.
axes(A)

Return the tuple of valid indices for array A.

Examples

julia> A = fill(1, (5,6,7));

julia> axes(A)
(Base.OneTo(5), Base.OneTo(6), Base.OneTo(7))
source
Base.axesMethod.
axes(A, d)

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

Examples

julia> A = fill(1, (5,6,7));

julia> axes(A, 2)
Base.OneTo(6)
source
Base.lengthMethod.
length(collection) -> Integer

Return the number of elements in the collection.

Use lastindex to get the last valid index of an indexable collection.

Examples

julia> length(1:5)
5

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

julia> length([1 2; 3 4])
4
source
Base.eachindexFunction.
eachindex(A...)

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). For other array types, return a specialized Cartesian range to efficiently index into the array with indices specified for every dimension. For other iterables, including strings and dictionaries, return an iterator object supporting arbitrary index types (e.g. unevenly spaced or non-integer indices).

If you supply more than one AbstractArray argument, eachindex will create an iterable object that is fast for all arguments (a UnitRange if all inputs have fast linear indexing, a CartesianIndices otherwise). If the arrays have different sizes and/or dimensionalities, eachindex will return an iterable that spans the largest range along each dimension.

Examples

julia> A = [1 2; 3 4];

julia> for i in eachindex(A) # linear indexing
           println(i)
       end
1
2
3
4

julia> for i in eachindex(view(A, 1:2, 1:1)) # Cartesian indexing
           println(i)
       end
CartesianIndex(1, 1)
CartesianIndex(2, 1)
source
Base.linearindicesFunction.
linearindices(A)

Return a UnitRange specifying the valid range of indices for A[i] where i is an Int. For arrays with conventional indexing (indices start at 1), or any multidimensional array, this is 1:length(A); however, for one-dimensional arrays with unconventional indices, this is axes(A, 1).

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

Examples

julia> A = fill(1, (5,6,7));

julia> b = linearindices(A);

julia> extrema(b)
(1, 210)
source
Base.IndexStyleType.
IndexStyle(A)
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 or cartesian indexing. If you decide to implement linear indexing, then you must set this trait for your array type:

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

The default is IndexCartesian().

Julia's internal indexing machinery will automatically (and invisibly) convert 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.conj!Function.
conj!(A)

Transform an array to its complex conjugate in-place.

See also conj.

Examples

julia> A = [1+im 2-im; 2+2im 3+im]
2×2 Array{Complex{Int64},2}:
 1+1im  2-1im
 2+2im  3+1im

julia> conj!(A);

julia> A
2×2 Array{Complex{Int64},2}:
 1-1im  2+1im
 2-2im  3-1im
source
Base.strideFunction.
stride(A, k::Integer)

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

Examples

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

julia> stride(A,2)
3

julia> stride(A,3)
12
source
Base.stridesFunction.
strides(A)

Return a tuple of the memory strides in each dimension.

Examples

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

julia> strides(A)
(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.broadcastFunction.
broadcast(f, As...)

Broadcasts the arrays, tuples, Refs and/or scalars As to a container of the appropriate type and dimensions. In this context, anything that is not a subtype of AbstractArray, Ref (except for Ptrs) or Tuple is considered a scalar. The resulting container is established by the following rules:

  • If all the arguments are scalars, it returns a scalar.

  • If the arguments are tuples and zero or more scalars, it returns a tuple.

  • If the arguments contain at least one array or Ref, it returns an array (expanding singleton dimensions), and treats Refs as 0-dimensional arrays, and tuples as 1-dimensional arrays.

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

julia> A = [1, 2, 3, 4, 5]
5-element Array{Int64,1}:
 1
 2
 3
 4
 5

julia> B = [1 2; 3 4; 5 6; 7 8; 9 10]
5×2 Array{Int64,2}:
 1   2
 3   4
 5   6
 7   8
 9  10

julia> broadcast(+, A, B)
5×2 Array{Int64,2}:
  2   3
  5   6
  8   9
 11  12
 14  15

julia> parse.(Int, ["1", "2"])
2-element Array{Int64,1}:
 1
 2

julia> abs.((1, -2))
(1, 2)

julia> broadcast(+, 1.0, (0, -2.0))
(1.0, -1.0)

julia> broadcast(+, 1.0, (0, -2.0), Ref(1))
2-element Array{Float64,1}:
 2.0
 0.0

julia> (+).([[0,2], [1,3]], Ref{Vector{Int}}([1,-1]))
2-element Array{Array{Int64,1},1}:
 [1, 1]
 [2, 2]

julia> string.(("one","two","three","four"), ": ", 1:4)
4-element Array{String,1}:
 "one: 1"
 "two: 2"
 "three: 3"
 "four: 4"
source
Base.broadcast!Function.
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).

source
@. 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

julia> x = 1.0:3.0; y = similar(x);

julia> @. y = x + 3 * sin(x)
3-element Array{Float64,1}:
 3.5244129544236893
 4.727892280477045
 3.4233600241796016
source
broadcast_getindex(A, inds...)

Equivalent to broadcasting the inds arrays to a common size and returning an array [A[ks...] for ks in zip(indsb...)] (where indsb would be the broadcast inds). The shape of the output is equal to the shape of each element of indsb.

Examples

julia> A = [11 12; 21 22]
2×2 Array{Int64,2}:
 11  12
 21  22

julia> A[1:2, 1:2]
2×2 Array{Int64,2}:
 11  12
 21  22

julia> broadcast_getindex(A, 1:2, 1:2)
2-element Array{Int64,1}:
 11
 22

julia> A[1:2, 2:-1:1]
2×2 Array{Int64,2}:
 12  11
 22  21

julia> broadcast_getindex(A, 1:2, 2:-1:1)
2-element Array{Int64,1}:
 12
 21
 ```
Because the indices are all vectors, these calls are like `[A[i[k], j[k]] for k = 1:2]`
where `i` and `j` are the two index vectors.

jldoctest julia> broadcast_getindex(A, 1:2, (1:2)') 2×2 Array{Int64,2}: 11 12 21 22

julia> broadcast_getindex(A, (1:2)', 1:2) 2×2 Array{Int64,2}: 11 21 12 22

julia> broadcast_getindex(A, [1 2 1; 1 2 2], [1, 2]) 2×3 Array{Int64,2}: 11 21 11 12 22 22 ```

source
broadcast_setindex!(A, X, inds...)

Efficient element-by-element setting of the values of A in a pattern established by inds. Equivalent to broadcasting the X and inds arrays to a common size, and then executing

for (is, js) in zip(zip(indsb), eachindex(Xb))
    A[is...] = Xb[js...]
end

where Xb and indsb are the broadcast X and inds.

See broadcast_getindex for examples of the treatment of inds.

source

For specializing broadcast on custom types, see

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

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

One then writes method(s) (at least broadcast_similar) operating on 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
broadcast_similar(f, ::BroadcastStyle, ::Type{ElType}, inds, As...)

Allocate an output object for broadcast, appropriate for the indicated Broadcast.BroadcastStyle. ElType and inds specify the desired element type and indices of the container. f is the broadcast operation, and As... are the arguments supplied to broadcast.

source
Base.broadcast_indices(::SrcStyle, A)

Compute the indices for objects A with BroadcastStyle SrcStyle. If needed, you can specialize this method for your styles. You should only need to provide a custom implementation for non-AbstractArrayStyles.

source

Broadcast.Scalar() is a BroadcastStyle indicating that an object is not treated as a container for the purposes of broadcasting. This is the default for objects that have not customized BroadcastStyle.

source

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:

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

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

struct MyArrayStyle <: Broadcast.AbstractArrayStyle{Any} end
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:

struct MyArrayStyleDim{N} <: Broadcast.AbstractArrayStyle{N} end
(::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

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

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 "wins" over Broadcast.Scalar but "loses" to any other Broadcast.ArrayStyle.

source

Indexing and assignment

Base.getindexMethod.
getindex(A, inds...)

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

Examples

julia> A = [1 2; 3 4]
2×2 Array{Int64,2}:
 1  2
 3  4

julia> getindex(A, 1)
1

julia> getindex(A, [2, 1])
2-element Array{Int64,1}:
 3
 1

julia> getindex(A, 2:4)
3-element Array{Int64,1}:
 3
 2
 4
source
Base.setindex!Method.
setindex!(A, X, inds...)

Store values from array X within some subset of A as specified by inds.

source
Base.copyto!Method.
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.

source
Base.isassignedFunction.
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

julia> isassigned(rand(3, 3), 5)
true

julia> isassigned(rand(3, 3), 3 * 3 + 1)
false

julia> mutable struct Foo end

julia> v = similar(rand(3), Foo)
3-element Array{Foo,1}:
 #undef
 #undef
 #undef

julia> isassigned(v, 1)
false
source
Base.ColonType.
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
CartesianIndex(i, j, k...)   -> I
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

julia> A = reshape(Vector(1:16), (2, 2, 2, 2))
2×2×2×2 Array{Int64,4}:
[:, :, 1, 1] =
 1  3
 2  4

[:, :, 2, 1] =
 5  7
 6  8

[:, :, 1, 2] =
  9  11
 10  12

[:, :, 2, 2] =
 13  15
 14  16

julia> A[CartesianIndex((1, 1, 1, 1))]
1

julia> A[CartesianIndex((1, 1, 1, 2))]
9

julia> A[CartesianIndex((1, 1, 2, 1))]
5
source
CartesianIndices(sz::Dims) -> R
CartesianIndices(istart:istop, jstart: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

for j = jstart:jstop
    for i = istart:istop
        ...
    end
end

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

CartesianIndices(A::AbstractArray) -> R

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

Examples

julia> foreach(println, CartesianIndices((2, 2, 2)))
CartesianIndex(1, 1, 1)
CartesianIndex(2, 1, 1)
CartesianIndex(1, 2, 1)
CartesianIndex(2, 2, 1)
CartesianIndex(1, 1, 2)
CartesianIndex(2, 1, 2)
CartesianIndex(1, 2, 2)
CartesianIndex(2, 2, 2)

julia> CartesianIndices(fill(1, (2,3)))
2×3 CartesianIndices{2,Tuple{Base.OneTo{Int64},Base.OneTo{Int64}}}:
  CartesianIndex(1, 1)  CartesianIndex(1, 2)  CartesianIndex(1, 3)
  CartesianIndex(2, 1)  CartesianIndex(2, 2)  CartesianIndex(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:

julia> cartesian = CartesianIndices(1:3,1:2)
3×2 CartesianIndices{2,Tuple{UnitRange{Int64},UnitRange{Int64}}}:
 CartesianIndex(1, 1)  CartesianIndex(1, 2)
 CartesianIndex(2, 1)  CartesianIndex(2, 2)
 CartesianIndex(3, 1)  CartesianIndex(3, 2)

julia> cartesian[4]
CartesianIndex(1, 2)

For cartesian to linear index conversion, see LinearIndices.

source
LinearIndices(inds::CartesianIndices) -> R
LinearIndices(sz::Dims) -> R
LinearIndices(istart:istop, jstart:jstop, ...) -> R

Define a mapping between cartesian indices and the corresponding linear index into a CartesianIndices.

Example

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

julia> linear = LinearIndices(1:3,1:2)
LinearIndices{2,Tuple{UnitRange{Int64},UnitRange{Int64}}} with indices 1:3×1:2:
  1  4
  2  5
  3  6

julia> linear[1,2]
4
source
Base.to_indicesFunction.
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.

source
Base.checkboundsFunction.
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

julia> A = rand(3, 3);

julia> checkbounds(Bool, A, 2)
true

julia> checkbounds(Bool, A, 3, 4)
false

julia> checkbounds(Bool, A, 1:3)
true

julia> checkbounds(Bool, A, 1:3, 2:4)
false
source
checkbounds(A, I...)

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

source
Base.checkindexFunction.
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.

Examples

julia> checkindex(Bool, 1:20, 8)
true

julia> checkindex(Bool, 1:20, 21)
false
source

Views (SubArrays and other view types)

Base.viewFunction.
view(A, inds...)

Like getindex, but returns a view into the parent array A with the given indices instead of making a copy. Calling getindex or setindex! on the returned SubArray computes the indices to the parent array on the fly without checking bounds.

julia> A = [1 2; 3 4]
2×2 Array{Int64,2}:
 1  2
 3  4

julia> b = view(A, :, 1)
2-element view(::Array{Int64,2}, :, 1) with eltype Int64:
 1
 3

julia> fill!(b, 0)
2-element view(::Array{Int64,2}, :, 1) with eltype Int64:
 0
 0

julia> A # Note A has changed even though we modified b
2×2 Array{Int64,2}:
 0  2
 0  4
source
Base.@viewMacro.
@view A[inds...]

Creates a SubArray from an indexing expression. This can only be applied directly to a reference expression (e.g. @view A[1,2:end]), and should not be used as the target of an assignment (e.g. @view(A[1,2:end]) = ...). See also @views to switch an entire block of code to use views for slicing.

julia> A = [1 2; 3 4]
2×2 Array{Int64,2}:
 1  2
 3  4

julia> b = @view A[:, 1]
2-element view(::Array{Int64,2}, :, 1) with eltype Int64:
 1
 3

julia> fill!(b, 0)
2-element view(::Array{Int64,2}, :, 1) with eltype Int64:
 0
 0

julia> A
2×2 Array{Int64,2}:
 0  2
 0  4
source
Base.@viewsMacro.
@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.

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.

Examples

julia> A = zeros(3, 3);

julia> @views for row in 1:3
           b = A[row, :]
           b[:] = row
       end

julia> A
3×3 Array{Float64,2}:
 1.0  1.0  1.0
 2.0  2.0  2.0
 3.0  3.0  3.0
source
Base.parentFunction.
parent(A)

Returns the "parent array" of an array view type (e.g., SubArray), or the array itself if it is not a view.

Examples

julia> A = [1 2; 3 4]
2×2 Array{Int64,2}:
 1  2
 3  4

julia> V = view(A, 1:2, :)
2×2 view(::Array{Int64,2}, 1:2, :) with eltype Int64:
 1  2
 3  4

julia> parent(V)
2×2 Array{Int64,2}:
 1  2
 3  4
source
Base.parentindicesFunction.
parentindices(A)

From an array view A, returns the corresponding indices in the parent.

source
Base.selectdimFunction.
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.

Examples

julia> A = [1 2 3 4; 5 6 7 8]
2×4 Array{Int64,2}:
 1  2  3  4
 5  6  7  8

julia> selectdim(A, 2, 3)
2-element view(::Array{Int64,2}, Base.OneTo(2), 3) with eltype Int64:
 3
 7
source
Base.reinterpretFunction.
reinterpret(type, A)

Change the type-interpretation of a block of memory. For arrays, this constructs a view of the array with the same binary data as the given array, but with the specified element type. For example, reinterpret(Float32, UInt32(7)) interprets the 4 bytes corresponding to UInt32(7) as a Float32.

Examples

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

julia> reinterpret(Float32, UInt32[1 2 3 4 5])
1×5 reinterpret(Float32, ::Array{UInt32,2}):
 1.4013e-45  2.8026e-45  4.2039e-45  5.60519e-45  7.00649e-45
source
Base.reshapeFunction.
reshape(A, dims...) -> R
reshape(A, dims) -> R

Return an array R 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 setting elements of R alters the values of A and vice versa.

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.

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

julia> reshape(A, (4, 4))
4×4 Array{Int64,2}:
 1  5   9  13
 2  6  10  14
 3  7  11  15
 4  8  12  16

julia> reshape(A, 2, :)
2×8 Array{Int64,2}:
 1  3  5  7   9  11  13  15
 2  4  6  8  10  12  14  16
source
Base.squeezeFunction.
squeeze(A, dims)

Remove the dimensions specified by dims from array A. Elements of dims must be unique and within the range 1:ndims(A). size(A,i) must equal 1 for all i in dims.

Examples

julia> a = reshape(Vector(1:4),(2,2,1,1))
2×2×1×1 Array{Int64,4}:
[:, :, 1, 1] =
 1  3
 2  4

julia> squeeze(a,3)
2×2×1 Array{Int64,3}:
[:, :, 1] =
 1  3
 2  4
source
Base.vecFunction.
vec(a::AbstractArray) -> Vector

Reshape the array a as a one-dimensional column vector. The resulting array shares the same underlying data as a, so modifying one will also modify the other.

Examples

julia> a = [1 2 3; 4 5 6]
2×3 Array{Int64,2}:
 1  2  3
 4  5  6

julia> vec(a)
6-element Array{Int64,1}:
 1
 4
 2
 5
 3
 6

See also reshape.

source

Concatenation and permutation

Base.catFunction.
cat(dims, A...)

Concatenate the input arrays along the specified dimensions in the iterable dims. For dimensions not in dims, all input arrays should have the same size, which will also be the size of the output array along that dimension. For dimensions in dims, the size of the output array is the sum of the sizes of the input arrays along that dimension. If dims is a single number, the different arrays are tightly stacked along that dimension. If dims is an iterable containing several dimensions, this allows one to construct block diagonal matrices and their higher-dimensional analogues by simultaneously increasing several dimensions for every new input array and putting zero blocks elsewhere. For example, cat([1,2], matrices...) builds a block diagonal matrix, i.e. a block matrix with matrices[1], matrices[2], ... as diagonal blocks and matching zero blocks away from the diagonal.

source
Base.vcatFunction.
vcat(A...)

Concatenate along dimension 1.

Examples

julia> a = [1 2 3 4 5]
1×5 Array{Int64,2}:
 1  2  3  4  5

julia> b = [6 7 8 9 10; 11 12 13 14 15]
2×5 Array{Int64,2}:
  6   7   8   9  10
 11  12  13  14  15

julia> vcat(a,b)
3×5 Array{Int64,2}:
  1   2   3   4   5
  6   7   8   9  10
 11  12  13  14  15

julia> c = ([1 2 3], [4 5 6])
([1 2 3], [4 5 6])

julia> vcat(c...)
2×3 Array{Int64,2}:
 1  2  3
 4  5  6
source
Base.hcatFunction.
hcat(A...)

Concatenate along dimension 2.

Examples

julia> a = [1; 2; 3; 4; 5]
5-element Array{Int64,1}:
 1
 2
 3
 4
 5

julia> b = [6 7; 8 9; 10 11; 12 13; 14 15]
5×2 Array{Int64,2}:
  6   7
  8   9
 10  11
 12  13
 14  15

julia> hcat(a,b)
5×3 Array{Int64,2}:
 1   6   7
 2   8   9
 3  10  11
 4  12  13
 5  14  15

julia> c = ([1; 2; 3], [4; 5; 6])
([1, 2, 3], [4, 5, 6])

julia> hcat(c...)
3×2 Array{Int64,2}:
 1  4
 2  5
 3  6
source
Base.hvcatFunction.
hvcat(rows::Tuple{Vararg{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.

Examples

julia> a, b, c, d, e, f = 1, 2, 3, 4, 5, 6
(1, 2, 3, 4, 5, 6)

julia> [a b c; d e f]
2×3 Array{Int64,2}:
 1  2  3
 4  5  6

julia> hvcat((3,3), a,b,c,d,e,f)
2×3 Array{Int64,2}:
 1  2  3
 4  5  6

julia> [a b;c d; e f]
3×2 Array{Int64,2}:
 1  2
 3  4
 5  6

julia> hvcat((2,2,2), a,b,c,d,e,f)
3×2 Array{Int64,2}:
 1  2
 3  4
 5  6

If the first argument is a single integer n, then all block rows are assumed to have n block columns.

source
Base.vectFunction.
vect(X...)

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

source
Base.flipdimFunction.
flipdim(A, d::Integer)

Reverse A in dimension d.

Examples

julia> b = [1 2; 3 4]
2×2 Array{Int64,2}:
 1  2
 3  4

julia> flipdim(b,2)
2×2 Array{Int64,2}:
 2  1
 4  3
source
Base.circshiftFunction.
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.

Examples

julia> b = reshape(Vector(1:16), (4,4))
4×4 Array{Int64,2}:
 1  5   9  13
 2  6  10  14
 3  7  11  15
 4  8  12  16

julia> circshift(b, (0,2))
4×4 Array{Int64,2}:
  9  13  1  5
 10  14  2  6
 11  15  3  7
 12  16  4  8

julia> circshift(b, (-1,0))
4×4 Array{Int64,2}:
 2  6  10  14
 3  7  11  15
 4  8  12  16
 1  5   9  13

julia> a = BitArray([true, true, false, false, true])
5-element BitArray{1}:
  true
  true
 false
 false
  true

julia> circshift(a, 1)
5-element BitArray{1}:
  true
  true
  true
 false
 false

julia> circshift(a, -1)
5-element BitArray{1}:
  true
 false
 false
  true
  true

See also circshift!.

source
Base.circshift!Function.
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.
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.

Examples

julia> src = reshape(Vector(1:16), (4,4))
4×4 Array{Int64,2}:
 1  5   9  13
 2  6  10  14
 3  7  11  15
 4  8  12  16

julia> dest = OffsetArray{Int}(uninitialized, (0:3,2:5))

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

julia> dest[1:3,2:4] == src[1:3,2:4]
true
source
Base.findallMethod.
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).

Examples

julia> A = [true, false, false, true]
4-element Array{Bool,1}:
  true
 false
 false
  true

julia> findall(A)
2-element Array{Int64,1}:
 1
 4

julia> A = [true false; false true]
2×2 Array{Bool,2}:
  true  false
 false   true

julia> findall(A)
2-element Array{Int64,1}:
 1
 4

julia> findall(falses(3))
0-element Array{Int64,1}
source
Base.findallMethod.
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

julia> x = [1, 3, 4]
3-element Array{Int64,1}:
 1
 3
 4

julia> findall(isodd, x)
2-element Array{Int64,1}:
 1
 2

julia> A = [1 2 0; 3 4 0]
2×3 Array{Int64,2}:
 1  2  0
 3  4  0
julia> findall(isodd, A)
2-element Array{CartesianIndex{2},1}:
 CartesianIndex(1, 1)
 CartesianIndex(2, 1)

julia> findall(!iszero, A)
4-element Array{CartesianIndex{2},1}:
 CartesianIndex(1, 1)
 CartesianIndex(2, 1)
 CartesianIndex(1, 2)
 CartesianIndex(2, 2)

julia> d = Dict(:A => 10, :B => -1, :C => 0)
Dict{Symbol,Int64} with 3 entries:
  :A => 10
  :B => -1
  :C => 0

julia> findall(x -> x >= 0, d)
2-element Array{Symbol,1}:
 :A
 :C
source
Base.findfirstMethod.
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).

Examples

julia> A = [false, false, true, false]
4-element Array{Bool,1}:
 false
 false
  true
 false

julia> findfirst(A)
3

julia> findfirst(falses(3)) == nothing
true

julia> A = [false false; true false]
2×2 Array{Bool,2}:
 false  false
  true  false

julia> findfirst(A)
CartesianIndex(2, 1)
source
Base.findfirstMethod.
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

julia> A = [1, 4, 2, 2]
4-element Array{Int64,1}:
 1
 4
 2
 2

julia> findfirst(iseven, A)
2

julia> findfirst(x -> x>10, A) == nothing
true

julia> findfirst(equalto(4), A)
2

julia> A = [1 4; 2 2]
2×2 Array{Int64,2}:
 1  4
 2  2

julia> findfirst(iseven, A)
CartesianIndex(2, 1)
source
Base.findlastMethod.
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).

Examples

julia> A = [true, false, true, false]
4-element Array{Bool,1}:
  true
 false
  true
 false

julia> findlast(A)
3

julia> A = falses(2,2);

julia> findlast(A) == nothing
true

julia> A = [true false; true false]
2×2 Array{Bool,2}:
 true  false
 true  false

julia> findlast(A)
CartesianIndex(2, 1)
source
Base.findlastMethod.
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

julia> A = [1, 2, 3, 4]
4-element Array{Int64,1}:
 1
 2
 3
 4

julia> findlast(isodd, A)
3

julia> findlast(x -> x > 5, A) == nothing
true

julia> A = [1 2; 3 4]
2×2 Array{Int64,2}:
 1  2
 3  4

julia> findlast(isodd, A)
CartesianIndex(2, 1)
source
Base.findnextMethod.
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

julia> A = [false, false, true, false]
4-element Array{Bool,1}:
 false
 false
  true
 false

julia> findnext(A, 1)
3

julia> findnext(A, 4) == nothing
true

julia> A = [false false; true false]
2×2 Array{Bool,2}:
 false  false
  true  false

julia> findnext(A, CartesianIndex(1, 1))
CartesianIndex(2, 1)
source
Base.findnextMethod.
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

A = [1, 4, 2, 2]
4-element Array{Int64,1}:
 1
 4
 2
 2

julia> findnext(isodd, A, 1)
1

julia> findnext(isodd, A, 2) == nothing
true

julia> A = [1 4; 2 2]
2×2 Array{Int64,2}:
 1  4
 2  2

julia> findnext(isodd, A, CartesianIndex(1, 1))
CartesianIndex(1, 1)
source
Base.findprevMethod.
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).

Examples

julia> A = [false, false, true, true]
4-element Array{Bool,1}:
 false
 false
  true
  true

julia> findprev(A, 3)
3

julia> findprev(A, 1) == nothing
true

julia> A = [false false; true true]
2×2 Array{Bool,2}:
 false  false
  true   true

julia> findprev(A, CartesianIndex(2, 1))
CartesianIndex(2, 1)
source
Base.findprevMethod.
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

julia> A = [4, 6, 1, 2]
4-element Array{Int64,1}:
 4
 6
 1
 2

julia> findprev(isodd, A, 1) == nothing
true

julia> findprev(isodd, A, 3)
3

julia> A = [4 6; 1 2]
2×2 Array{Int64,2}:
 4  6
 1  2

julia> findprev(isodd, A, CartesianIndex(1, 2))
CartesianIndex(2, 1)
source
Base.permutedimsFunction.
permutedims(A::AbstractArray, perm)

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

See also: PermutedDimsArray.

Examples

julia> A = reshape(Vector(1:8), (2,2,2))
2×2×2 Array{Int64,3}:
[:, :, 1] =
 1  3
 2  4

[:, :, 2] =
 5  7
 6  8

julia> permutedims(A, [3, 2, 1])
2×2×2 Array{Int64,3}:
[:, :, 1] =
 1  3
 5  7

[:, :, 2] =
 2  4
 6  8
source
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

julia> a = [1 2; 3 4];

julia> b = [5 6; 7 8];

julia> c = [9 10; 11 12];

julia> d = [13 14; 15 16];

julia> X = [[a] [b]; [c] [d]]
2×2 Array{Array{Int64,2},2}:
 [1 2; 3 4]     [5 6; 7 8]
 [9 10; 11 12]  [13 14; 15 16]

julia> permutedims(X)
2×2 Array{Array{Int64,2},2}:
 [1 2; 3 4]  [9 10; 11 12]
 [5 6; 7 8]  [13 14; 15 16]

julia> transpose(X)
2×2 LinearAlgebra.Transpose{LinearAlgebra.Transpose{Int64,Array{Int64,2}},Array{Array{Int64,2},2}}:
 [1 3; 2 4]  [9 11; 10 12]
 [5 7; 6 8]  [13 15; 14 16]
source
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

julia> permutedims([1, 2, 3, 4])
1×4 Array{Int64,2}:
 1  2  3  4

julia> V = [[[1 2; 3 4]]; [[5 6; 7 8]]]
2-element Array{Array{Int64,2},1}:
 [1 2; 3 4]
 [5 6; 7 8]

julia> permutedims(V)
1×2 Array{Array{Int64,2},2}:
 [1 2; 3 4]  [5 6; 7 8]

julia> transpose(V)
1×2 LinearAlgebra.Transpose{LinearAlgebra.Transpose{Int64,Array{Int64,2}},Array{Array{Int64,2},1}}:
 [1 3; 2 4]  [5 7; 6 8]
source
Base.permutedims!Function.
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
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.

Examples

julia> A = rand(3,5,4);

julia> B = PermutedDimsArray(A, (3,1,2));

julia> size(B)
(4, 3, 5)

julia> B[3,1,2] == A[1,2,3]
true
source
Base.promote_shapeFunction.
promote_shape(s1, s2)

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

julia> a = fill(1, (3,4,1,1,1));

julia> b = fill(1, (3,4));

julia> promote_shape(a,b)
(Base.OneTo(3), Base.OneTo(4), Base.OneTo(1), Base.OneTo(1), Base.OneTo(1))

julia> promote_shape((2,3,1,4), (2, 3, 1, 4, 1))
(2, 3, 1, 4, 1)
source

Array functions

Base.accumulateMethod.
accumulate(op, A, dim::Integer)

Cumulative operation op along the dimension dim. 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

Examples

julia> accumulate(+, fill(1, 3, 3), 1)
3×3 Array{Int64,2}:
 1  1  1
 2  2  2
 3  3  3

julia> accumulate(+, fill(1, 3, 3), 2)
3×3 Array{Int64,2}:
 1  2  3
 1  2  3
 1  2  3
source
Base.accumulate!Function.
accumulate!(op, B, A, dim::Integer)

Cumulative operation op on A along the dimension dim, storing the result in B. See also accumulate.

Examples

julia> A = [1 2; 3 4];

julia> B = [0 0; 0 0];

julia> accumulate!(-, B, A, 1);

julia> B
2×2 Array{Int64,2}:
  1   2
 -2  -2

julia> accumulate!(-, B, A, 2);

julia> B
2×2 Array{Int64,2}:
 1  -1
 3  -1
source
accumulate!(op, y, x::AbstractVector)

Cumulative operation op on a vector x, storing the result in y. See also accumulate.

Examples

``jldoctest julia> x = [1, 0, 2, 0, 3];

julia> y = [0, 0, 0, 0, 0];

julia> accumulate!(+, y, x);

julia> y 5-element Array{Int64,1}: 1 1 3 3 6 ```

source
Base.cumprodFunction.
cumprod(A, dim::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

julia> a = [1 2 3; 4 5 6]
2×3 Array{Int64,2}:
 1  2  3
 4  5  6

julia> cumprod(a,1)
2×3 Array{Int64,2}:
 1   2   3
 4  10  18

julia> cumprod(a,2)
2×3 Array{Int64,2}:
 1   2    6
 4  20  120
source
cumprod(x::AbstractVector)

Cumulative product of a vector. 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

julia> cumprod(fill(1//2, 3))
3-element Array{Rational{Int64},1}:
 1//2
 1//4
 1//8

julia> cumprod([fill(1//3, 2, 2) for i in 1:3])
3-element Array{Array{Rational{Int64},2},1}:
 Rational{Int64}[1//3 1//3; 1//3 1//3]
 Rational{Int64}[2//9 2//9; 2//9 2//9]
 Rational{Int64}[4//27 4//27; 4//27 4//27]
source
Base.cumprod!Function.
cumprod!(B, A, dim::Integer)

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

source
cumprod!(y::AbstractVector, x::AbstractVector)

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

source
Base.cumsumFunction.
cumsum(A, dim::Integer)

Cumulative sum along the dimension dim. 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

julia> a = [1 2 3; 4 5 6]
2×3 Array{Int64,2}:
 1  2  3
 4  5  6

julia> cumsum(a,1)
2×3 Array{Int64,2}:
 1  2  3
 5  7  9

julia> cumsum(a,2)
2×3 Array{Int64,2}:
 1  3   6
 4  9  15
source
cumsum(x::AbstractVector)

Cumulative sum a vector. 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

julia> cumsum([1, 1, 1])
3-element Array{Int64,1}:
 1
 2
 3

julia> cumsum([fill(1, 2) for i in 1:3])
3-element Array{Array{Int64,1},1}:
 [1, 1]
 [2, 2]
 [3, 3]
source
Base.cumsum!Function.
cumsum!(B, A, dim::Integer)

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

source
cumsum!(y::AbstractVector, x::AbstractVector)

Cumulative sum of a vector x, storing the result in y. See also cumsum.

source
LinearAlgebra.diffFunction.
diff(A::AbstractVector)
diff(A::AbstractMatrix, dim::Integer)

Finite difference operator of matrix or vector A. If A is a matrix, specify the dimension over which to operate with the dim argument.

Examples

julia> a = [2 4; 6 16]
2×2 Array{Int64,2}:
 2   4
 6  16

julia> diff(a,2)
2×1 Array{Int64,2}:
  2
 10

julia> diff(vec(a))
3-element Array{Int64,1}:
  4
 -2
 12
source
Base.repeatFunction.
repeat(A::AbstractArray, counts::Integer...)

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

Examples

julia> repeat([1, 2, 3], 2)
6-element Array{Int64,1}:
 1
 2
 3
 1
 2
 3

julia> repeat([1, 2, 3], 2, 3)
6×3 Array{Int64,2}:
 1  1  1
 2  2  2
 3  3  3
 1  1  1
 2  2  2
 3  3  3
source
repeat(A::AbstractArray; inner=ntuple(x->1, ndims(A)), outer=ntuple(x->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

julia> repeat(1:2, inner=2)
4-element Array{Int64,1}:
 1
 1
 2
 2

julia> repeat(1:2, outer=2)
4-element Array{Int64,1}:
 1
 2
 1
 2

julia> repeat([1 2; 3 4], inner=(2, 1), outer=(1, 3))
4×6 Array{Int64,2}:
 1  2  1  2  1  2
 1  2  1  2  1  2
 3  4  3  4  3  4
 3  4  3  4  3  4
source
repeat(s::AbstractString, r::Integer)

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

See also: ^

Examples

julia> repeat("ha", 3)
"hahaha"
source
repeat(c::Char, r::Integer) -> String

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

Examples

julia> repeat('A', 3)
"AAA"
source
Base.rot180Function.
rot180(A)

Rotate matrix A 180 degrees.

Examples

julia> a = [1 2; 3 4]
2×2 Array{Int64,2}:
 1  2
 3  4

julia> rot180(a)
2×2 Array{Int64,2}:
 4  3
 2  1
source
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

julia> a = [1 2; 3 4]
2×2 Array{Int64,2}:
 1  2
 3  4

julia> rot180(a,1)
2×2 Array{Int64,2}:
 4  3
 2  1

julia> rot180(a,2)
2×2 Array{Int64,2}:
 1  2
 3  4
source
Base.rotl90Function.
rotl90(A)

Rotate matrix A left 90 degrees.

Examples

julia> a = [1 2; 3 4]
2×2 Array{Int64,2}:
 1  2
 3  4

julia> rotl90(a)
2×2 Array{Int64,2}:
 2  4
 1  3
source
rotl90(A, k)

Rotate matrix A left 90 degrees an integer k number of times. If k is zero or a multiple of four, this is equivalent to a copy.

Examples

julia> a = [1 2; 3 4]
2×2 Array{Int64,2}:
 1  2
 3  4

julia> rotl90(a,1)
2×2 Array{Int64,2}:
 2  4
 1  3

julia> rotl90(a,2)
2×2 Array{Int64,2}:
 4  3
 2  1

julia> rotl90(a,3)
2×2 Array{Int64,2}:
 3  1
 4  2

julia> rotl90(a,4)
2×2 Array{Int64,2}:
 1  2
 3  4
source
Base.rotr90Function.
rotr90(A)

Rotate matrix A right 90 degrees.

Examples

julia> a = [1 2; 3 4]
2×2 Array{Int64,2}:
 1  2
 3  4

julia> rotr90(a)
2×2 Array{Int64,2}:
 3  1
 4  2
source
rotr90(A, k)

Rotate matrix A right 90 degrees an integer k number of times. If k is zero or a multiple of four, this is equivalent to a copy.

Examples

julia> a = [1 2; 3 4]
2×2 Array{Int64,2}:
 1  2
 3  4

julia> rotr90(a,1)
2×2 Array{Int64,2}:
 3  1
 4  2

julia> rotr90(a,2)
2×2 Array{Int64,2}:
 4  3
 2  1

julia> rotr90(a,3)
2×2 Array{Int64,2}:
 2  4
 1  3

julia> rotr90(a,4)
2×2 Array{Int64,2}:
 1  2
 3  4
source
Base.reducedimFunction.
reducedim(f, A, region[, v0])

Reduce 2-argument function f along dimensions of A. region is a vector specifying the dimensions to reduce, and v0 is the initial value to use in the reductions. For +, *, max and min the v0 argument is optional.

The associativity of the reduction is implementation-dependent; if you need a particular associativity, e.g. left-to-right, you should write your own loop. See documentation for reduce.

Examples

julia> a = reshape(Vector(1:16), (4,4))
4×4 Array{Int64,2}:
 1  5   9  13
 2  6  10  14
 3  7  11  15
 4  8  12  16

julia> reducedim(max, a, 2)
4×1 Array{Int64,2}:
 13
 14
 15
 16

julia> reducedim(max, a, 1)
1×4 Array{Int64,2}:
 4  8  12  16
source
Base.mapreducedimFunction.
mapreducedim(f, op, A, region[, v0])

Evaluates to the same as reducedim(op, map(f, A), region, f(v0)), but is generally faster because the intermediate array is avoided.

Examples

julia> a = reshape(Vector(1:16), (4,4))
4×4 Array{Int64,2}:
 1  5   9  13
 2  6  10  14
 3  7  11  15
 4  8  12  16

julia> mapreducedim(isodd, *, a, 1)
1×4 Array{Bool,2}:
 false  false  false  false

julia> mapreducedim(isodd, |, a, 1, true)
1×4 Array{Bool,2}:
 true  true  true  true
source
Base.mapslicesFunction.
mapslices(f, A, dims)

Transform the given dimensions of array A using function f. f is called on each slice of A of the form A[...,:,...,:,...]. dims is an integer vector specifying where the colons go in this expression. The results are concatenated along the remaining dimensions. For example, if dims is [1,2] and A is 4-dimensional, f is called on A[:,:,i,j] for all i and j.

Examples

julia> a = reshape(Vector(1:16),(2,2,2,2))
2×2×2×2 Array{Int64,4}:
[:, :, 1, 1] =
 1  3
 2  4

[:, :, 2, 1] =
 5  7
 6  8

[:, :, 1, 2] =
  9  11
 10  12

[:, :, 2, 2] =
 13  15
 14  16

julia> mapslices(sum, a, [1,2])
1×1×2×2 Array{Int64,4}:
[:, :, 1, 1] =
 10

[:, :, 2, 1] =
 26

[:, :, 1, 2] =
 42

[:, :, 2, 2] =
 58
source

Combinatorics

Base.invpermFunction.
invperm(v)

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

Examples

julia> v = [2; 4; 3; 1];

julia> invperm(v)
4-element Array{Int64,1}:
 4
 1
 3
 2

julia> A = ['a','b','c','d'];

julia> B = A[v]
4-element Array{Char,1}:
 'b'
 'd'
 'c'
 'a'

julia> B[invperm(v)]
4-element Array{Char,1}:
 'a'
 'b'
 'c'
 'd'
source
Base.ispermFunction.
isperm(v) -> Bool

Return true if v is a valid permutation.

Examples

julia> isperm([1; 2])
true

julia> isperm([1; 3])
false
source
Base.permute!Method.
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 generally faster than permute!(v,p) for large vectors.

See also invpermute!.

Examples

julia> A = [1, 1, 3, 4];

julia> perm = [2, 4, 3, 1];

julia> permute!(A, perm);

julia> A
4-element Array{Int64,1}:
 1
 4
 3
 1
source
Base.invpermute!Function.
invpermute!(v, p)

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

Examples

julia> A = [1, 1, 3, 4];

julia> perm = [2, 4, 3, 1];

julia> invpermute!(A, perm);

julia> A
4-element Array{Int64,1}:
 4
 1
 3
 1
source
Base.reverseFunction.
reverse(v [, start=1 [, stop=length(v) ]] )

Return a copy of v reversed from start to stop. See also Iterators.reverse for reverse-order iteration without making a copy.

Examples

julia> A = Vector(1:5)
5-element Array{Int64,1}:
 1
 2
 3
 4
 5

julia> reverse(A)
5-element Array{Int64,1}:
 5
 4
 3
 2
 1

julia> reverse(A, 1, 4)
5-element Array{Int64,1}:
 4
 3
 2
 1
 5

julia> reverse(A, 3, 5)
5-element Array{Int64,1}:
 1
 2
 5
 4
 3
source
reverse(s::AbstractString) -> AbstractString

Reverses a string. Technically, this function reverses the codepoints in a string and its main utility is for reversed-order string processing, especially for reversed regular-expression searches. See also reverseind to convert indices in s to indices in reverse(s) and vice-versa, and graphemes from module Unicode to operate on user-visible "characters" (graphemes) rather than codepoints. See also Iterators.reverse for reverse-order iteration without making a copy. Custom string types must implement the reverse function themselves and should typically return a string with the same type and encoding. If they return a string with a different encoding, they must also override reverseind for that string type to satisfy s[reverseind(s,i)] == reverse(s)[i].

Examples

julia> reverse("JuliaLang")
"gnaLailuJ"

julia> reverse("ax̂e") # combining characters can lead to surprising results
"êxa"

julia> using Unicode

julia> join(reverse(collect(graphemes("ax̂e")))) # reverses graphemes
"ex̂a"
source
Base.reverseindFunction.
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

julia> r = reverse("Julia")
"ailuJ"

julia> for i in 1:length(r)
           print(r[reverseind("Julia", i)])
       end
Julia
source
Base.reverse!Function.
reverse!(v [, start=1 [, stop=length(v) ]]) -> v

In-place version of reverse.

Examples

julia> A = Vector(1:5)
5-element Array{Int64,1}:
 1
 2
 3
 4
 5

julia> reverse!(A);

julia> A
5-element Array{Int64,1}:
 5
 4
 3
 2
 1
source

BitArrays

BitArrays are space-efficient "packed" boolean arrays, which store one bit per boolean value. They can be used similarly to Array{Bool} arrays (which store one byte per boolean value), and can be converted to/from the latter via Array(bitarray) and BitArray(array), respectively.

Base.flipbits!Function.
flipbits!(B::BitArray{N}) -> BitArray{N}

Performs a bitwise not operation on B. See ~.

Examples

julia> A = trues(2,2)
2×2 BitArray{2}:
 true  true
 true  true

julia> flipbits!(A)
2×2 BitArray{2}:
 false  false
 false  false
source