Arrays
Constructors and Types
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.
1. AbstractVector{T}
Supertype for one-dimensional arrays (or array-like types) with elements of type T. Alias for AbstractArray{T,1}.
1. AbstractMatrix{T}
Supertype for two-dimensional arrays (or array-like types) with elements of type T. Alias for AbstractArray{T,2}.
1. AbstractVecOrMat{T}
Union type of AbstractVector{T} and AbstractMatrix{T}.
1. Array{T,N} <: AbstractArray{T,N}
N-dimensional dense array with elements of type T.
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. See undef.
Examples
1. julia> A = Array{Float64,2}(undef, 2, 3) # N given explicitly
2. 2×3 Array{Float64,2}:
3. 6.90198e-310 6.90198e-310 6.90198e-310
4. 6.90198e-310 6.90198e-310 0.0
6. julia> B = Array{Float64}(undef, 2) # N determined by the input
7. 2-element Array{Float64,1}:
8. 1.87103e-320
9. 0.0
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 Array{Union{Nothing, String},1}:
3. nothing
4. nothing
6. julia> Array{Union{Nothing, Int}}(nothing, 2, 3)
7. 2×3 Array{Union{Nothing, Int64},2}:
8. nothing nothing nothing
9. nothing nothing nothing
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 Array{Union{Missing, String},1}:
3. missing
4. missing
6. julia> Array{Union{Missing, Int}}(missing, 2, 3)
7. 2×3 Array{Union{Missing, Int64},2}:
8. missing missing missing
9. missing missing missing
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
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.
Examples
1. julia> Array{Float64,1}(undef, 3)
2. 3-element Array{Float64,1}:
3. 2.2752528595e-314
4. 2.202942107e-314
5. 2.275252907e-314
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}.
1. Vector{T}(undef, n)
Construct an uninitialized Vector{T} of length n. See undef.
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
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 Array{Union{Nothing, String},1}:
3. nothing
4. nothing
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 Array{Union{Missing, String},1}:
3. missing
4. missing
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}.
1. Matrix{T}(undef, m, n)
Construct an uninitialized Matrix{T} of size m×n. See undef.
Examples
1. julia> Matrix{Float64}(undef, 2, 3)
2. 2×3 Array{Float64,2}:
3. 6.93517e-310 6.93517e-310 6.93517e-310
4. 6.93517e-310 6.93517e-310 1.29396e-320
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 Array{Union{Nothing, String},2}:
3. nothing nothing nothing
4. nothing nothing nothing
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 Array{Union{Missing, String},2}:
3. missing missing missing
4. missing missing missing
1. VecOrMat{T}
Union type of Vector{T} and Matrix{T}.
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.
1. DenseVector{T}
One-dimensional DenseArray with elements of type T. Alias for DenseArray{T,1}.
1. DenseMatrix{T}
Two-dimensional DenseArray with elements of type T. Alias for DenseArray{T,2}.
1. DenseVecOrMat{T}
Union type of DenseVector{T} and DenseMatrix{T}.
1. StridedArray{T, N}
An N dimensional strided array with elements of type T. These arrays follow the strided array interface. 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.
1. StridedVector{T}
One dimensional StridedArray with elements of type T.
1. StridedMatrix{T}
Two dimensional StridedArray with elements of type T.
1. StridedVecOrMat{T}
Union type of StridedVector and StridedMatrix with elements of type T.
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 Array{Int8,1}:
3. 1
4. 2
5. 3
7. julia> getindex(Int8, 1, 2, 3)
8. 3-element Array{Int8,1}:
9. 1
10. 2
11. 3
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.
Examples
1. julia> zeros(1)
2. 1-element Array{Float64,1}:
3. 0.0
5. julia> zeros(Int8, 2, 3)
6. 2×3 Array{Int8,2}:
7. 0 0 0
8. 0 0 0
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 Array{Float64,2}:
3. 1.0 1.0
5. julia> ones(ComplexF64, 2, 3)
6. 2×3 Array{Complex{Float64},2}:
7. 1.0+0.0im 1.0+0.0im 1.0+0.0im
8. 1.0+0.0im 1.0+0.0im 1.0+0.0im
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.
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 BitArray{2}:
3. 0 0
4. 0 0
6. julia> BitArray(undef, (3, 1))
7. 3×1 BitArray{2}:
8. 0
9. 0
10. 0
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 BitArray{2}:
3. 1 0
4. 0 1
6. julia> BitArray(x+y == 3 for x = 1:2, y = 1:3)
7. 2×3 BitArray{2}:
8. 0 1 0
9. 1 0 0
11. julia> BitArray(x+y == 3 for x = 1:2 for y = 1:3)
12. 6-element BitArray{1}:
13. 0
14. 1
15. 0
16. 1
17. 0
18. 0
1. trues(dims)
Create a BitArray with all values set to true.
Examples
1. julia> trues(2,3)
2. 2×3 BitArray{2}:
3. 1 1 1
4. 1 1 1
1. falses(dims)
Create a BitArray with all values set to false.
Examples
1. julia> falses(2,3)
2. 2×3 BitArray{2}:
3. 0 0 0
4. 0 0 0
1. fill(x, dims::Tuple)
2. 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.
dims may be specified as either a tuple or a sequence of arguments. For example, the common idiom fill(x) creates a zero-dimensional array containing the single value x.
Examples
1. julia> fill(1.0, (5,5))
2. 5×5 Array{Float64,2}:
3. 1.0 1.0 1.0 1.0 1.0
4. 1.0 1.0 1.0 1.0 1.0
5. 1.0 1.0 1.0 1.0 1.0
6. 1.0 1.0 1.0 1.0 1.0
7. 1.0 1.0 1.0 1.0 1.0
9. julia> fill(0.5, 1, 2)
10. 1×2 Array{Float64,2}:
11. 0.5 0.5
13. julia> fill(42)
14. 0-dimensional Array{Int64,0}:
15. 42
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.
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 Array{Float64,2}:
3. 0.0 0.0 0.0
4. 0.0 0.0 0.0
6. julia> fill!(A, 2.)
7. 2×3 Array{Float64,2}:
8. 2.0 2.0 2.0
9. 2.0 2.0 2.0
11. julia> a = [1, 1, 1]; A = fill!(Vector{Vector{Int}}(undef, 3), a); a[1] = 2; A
12. 3-element Array{Array{Int64,1},1}:
13. [2, 1, 1]
14. [2, 1, 1]
15. [2, 1, 1]
17. julia> x = 0; f() = (global x += 1; x); fill!(Vector{Int}(undef, 3), f())
18. 3-element Array{Int64,1}:
19. 1
20. 1
21. 1
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 Array{Int64,2}:
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 BitArray{1}:
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 Array{Float64,2}:
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
1. similar(storagetype, axes)
Create an uninitialized mutable array analogous to that specified by storagetype, but with axes specified by the last argument. storagetype might be a type or a function.
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.
Basic functions
1. ndims(A::AbstractArray) -> Integer
Return the number of dimensions of A.
Examples
1. julia> A = fill(1, (3,4,5));
3. julia> ndims(A)
4. 3
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.
Examples
1. julia> A = fill(1, (2,3,4));
3. julia> size(A)
4. (2, 3, 4)
6. julia> size(A, 2)
7. 3
1. axes(A)
Return the tuple of valid indices for array A.
Examples
1. julia> A = fill(1, (5,6,7));
3. julia> axes(A)
4. (Base.OneTo(5), Base.OneTo(6), Base.OneTo(7))
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));
3. julia> axes(A, 2)
4. Base.OneTo(6)
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
4. julia> length([1 2; 3 4])
5. 4
1. 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, a DimensionMismatch exception will be thrown.
Examples
1. julia> A = [1 2; 3 4];
3. julia> for i in eachindex(A) # linear indexing
4. println(i)
5. end
6. 1
7. 2
8. 3
9. 4
11. julia> for i in eachindex(view(A, 1:2, 1:1)) # Cartesian indexing
12. println(i)
13. end
14. CartesianIndex(1, 1)
15. CartesianIndex(2, 1)
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.
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.
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.
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 Array{Complex{Int64},2}:
3. 1+1im 2-1im
4. 2+2im 3+1im
6. julia> conj!(A);
8. julia> A
9. 2×2 Array{Complex{Int64},2}:
10. 1-1im 2+1im
11. 2-2im 3-1im
1. stride(A, k::Integer)
Return the distance in memory (in number of elements) between adjacent elements in dimension k.
Examples
1. julia> A = fill(1, (3,4,5));
3. julia> stride(A,2)
4. 3
6. julia> stride(A,3)
7. 12
1. strides(A)
Return a tuple of the memory strides in each dimension.
Examples
1. julia> A = fill(1, (3,4,5));
3. julia> strides(A)
4. (1, 3, 12)
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.
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 Array{Int64,1}:
3. 1
4. 2
5. 3
6. 4
7. 5
9. julia> B = [1 2; 3 4; 5 6; 7 8; 9 10]
10. 5×2 Array{Int64,2}:
11. 1 2
12. 3 4
13. 5 6
14. 7 8
15. 9 10
17. julia> broadcast(+, A, B)
18. 5×2 Array{Int64,2}:
19. 2 3
20. 5 6
21. 8 9
22. 11 12
23. 14 15
25. julia> parse.(Int, ["1", "2"])
26. 2-element Array{Int64,1}:
27. 1
28. 2
30. julia> abs.((1, -2))
31. (1, 2)
33. julia> broadcast(+, 1.0, (0, -2.0))
34. (1.0, -1.0)
36. julia> (+).([[0,2], [1,3]], Ref{Vector{Int}}([1,-1]))
37. 2-element Array{Array{Int64,1},1}:
38. [1, 1]
39. [2, 2]
41. julia> string.(("one","two","three","four"), ": ", 1:4)
42. 4-element Array{String,1}:
43. "one: 1"
44. "two: 2"
45. "three: 3"
46. "four: 4"
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];
3. julia> broadcast!(+, B, A, (0, -2.0));
5. julia> B
6. 2-element Array{Float64,1}:
7. 1.0
8. -2.0
10. julia> A
11. 2-element Array{Float64,1}:
12. 1.0
13. 0.0
15. julia> broadcast!(+, A, A, (0, -2.0));
17. julia> A
18. 2-element Array{Float64,1}:
19. 1.0
20. -2.0
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);
3. julia> @. y = x + 3 * sin(x)
4. 3-element Array{Float64,1}:
5. 3.5244129544236893
6. 4.727892280477045
7. 3.4233600241796016
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
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.
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.
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.
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.
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 Array{Int64,1}:
3. 1
4. 2
5. 3
7. julia> Broadcast.broadcastable(Int) # Types don't support axes, indexing, or iteration but are commonly used as scalars
8. Base.RefValue{Type{Int64}}(Int64)
10. julia> Broadcast.broadcastable("hello") # Strings break convention of matching iteration and act like a scalar instead
11. Base.RefValue{String}("hello")
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))
4. julia> Broadcast.combine_axes(1, 1, 1)
5. ()
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}()
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}()
4. julia> Broadcast.result_style(Broadcast.Unknown(), Broadcast.DefaultArrayStyle{1}())
5. Base.Broadcast.DefaultArrayStyle{1}()
Indexing and assignment
1. 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
1. julia> A = [1 2; 3 4]
2. 2×2 Array{Int64,2}:
3. 1 2
4. 3 4
6. julia> getindex(A, 1)
7. 1
9. julia> getindex(A, [2, 1])
10. 2-element Array{Int64,1}:
11. 3
12. 1
14. julia> getindex(A, 2:4)
15. 3-element Array{Int64,1}:
16. 3
17. 2
18. 4
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...).
Examples
1. julia> A = zeros(2,2);
3. julia> setindex!(A, [10, 20], [1, 2]);
5. julia> A[[3, 4]] = [30, 40];
7. julia> A
8. 2×2 Array{Float64,2}:
9. 10.0 30.0
10. 20.0 40.0
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.
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
4. julia> isassigned(rand(3, 3), 3 * 3 + 1)
5. false
7. julia> mutable struct Foo end
9. julia> v = similar(rand(3), Foo)
10. 3-element Array{Foo,1}:
11. #undef
12. #undef
13. #undef
15. julia> isassigned(v, 1)
16. false
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 :.
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
7. [:, :, 2, 1] =
8. 5 7
9. 6 8
11. [:, :, 1, 2] =
12. 9 11
13. 10 12
15. [:, :, 2, 2] =
16. 13 15
17. 14 16
19. julia> A[CartesianIndex((1, 1, 1, 1))]
20. 1
22. julia> A[CartesianIndex((1, 1, 1, 2))]
23. 9
25. julia> A[CartesianIndex((1, 1, 2, 1))]
26. 5
1. CartesianIndices(sz::Dims) -> R
2. 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
1. for j = jstart:jstop
2. for i = istart: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.
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)
11. julia> CartesianIndices(fill(1, (2,3)))
12. 2×3 CartesianIndices{2,Tuple{Base.OneTo{Int64},Base.OneTo{Int64}}}:
13. CartesianIndex(1, 1) CartesianIndex(1, 2) CartesianIndex(1, 3)
14. 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:
1. julia> cartesian = CartesianIndices((1:3, 1:2))
2. 3×2 CartesianIndices{2,Tuple{UnitRange{Int64},UnitRange{Int64}}}:
3. CartesianIndex(1, 1) CartesianIndex(1, 2)
4. CartesianIndex(2, 1) CartesianIndex(2, 2)
5. CartesianIndex(3, 1) CartesianIndex(3, 2)
7. julia> cartesian[4]
8. CartesianIndex(1, 2)
Broadcasting
CartesianIndices support broadcasting arithmetic (+ and -) with
(本文超出站点单文档体积上限,已截断)
