Core.AbstractArray
—TypeAbstractArray{T,N}
Supertype forN
-dimensional arrays (or array-like types) with elements of typeT
.Array
and other types are subtypes of this. See the manual section on theAbstractArray
interface.
See also:AbstractVector
,AbstractMatrix
,eltype
,ndims
.
Base.AbstractVector
—TypeAbstractVector{T}
Supertype for one-dimensional arrays (or array-like types) with elements of typeT
. Alias forAbstractArray{T,1}
.
Base.AbstractMatrix
—TypeAbstractMatrix{T}
Supertype for two-dimensional arrays (or array-like types) with elements of typeT
. Alias forAbstractArray{T,2}
.
Base.AbstractVecOrMat
—TypeAbstractVecOrMat{T}
Union type ofAbstractVector{T}
andAbstractMatrix{T}
.
Core.Array
—TypeArray{T,N} <: AbstractArray{T,N}
N
-dimensional dense array with elements of typeT
.
Core.Array
—MethodArray{T}(undef, dims)Array{T,N}(undef, dims)
Construct an uninitializedN
-dimensionalArray
containing elements of typeT
.N
can either be supplied explicitly, as inArray{T,N}(undef, dims)
, or be determined by the length or number ofdims
.dims
may be a tuple or a series of integer arguments corresponding to the lengths in each dimension. If the rankN
is supplied explicitly, then it must match the length or number ofdims
. Hereundef
is theUndefInitializer
.
Examples
julia> A = Array{Float64, 2}(undef, 2, 3) # N given explicitly2×3 Matrix{Float64}: 6.90198e-310 6.90198e-310 6.90198e-310 6.90198e-310 6.90198e-310 0.0julia> B = Array{Float64}(undef, 4) # N determined by the input4-element Vector{Float64}: 2.360075077e-314 NaN 2.2671131793e-314 2.299821756e-314julia> similar(B, 2, 4, 1) # use typeof(B), and the given size2×4×1 Array{Float64, 3}:[:, :, 1] = 2.26703e-314 2.26708e-314 0.0 2.80997e-314 0.0 2.26703e-314 2.26708e-314 0.0
Core.Array
—MethodArray{T}(nothing, dims)Array{T,N}(nothing, dims)
Construct anN
-dimensionalArray
containing elements of typeT
, initialized withnothing
entries. Element typeT
must be able to hold these values, i.e.Nothing <: T
.
Examples
julia> Array{Union{Nothing, String}}(nothing, 2)2-element Vector{Union{Nothing, String}}: nothing nothingjulia> Array{Union{Nothing, Int}}(nothing, 2, 3)2×3 Matrix{Union{Nothing, Int64}}: nothing nothing nothing nothing nothing nothing
Core.Array
—MethodArray{T}(missing, dims)Array{T,N}(missing, dims)
Construct anN
-dimensionalArray
containing elements of typeT
, initialized withmissing
entries. Element typeT
must be able to hold these values, i.e.Missing <: T
.
Examples
julia> Array{Union{Missing, String}}(missing, 2)2-element Vector{Union{Missing, String}}: missing missingjulia> Array{Union{Missing, Int}}(missing, 2, 3)2×3 Matrix{Union{Missing, Int64}}: missing missing missing missing missing missing
Core.UndefInitializer
—TypeUndefInitializer
Singleton type used in array initialization, indicating the array-constructor-caller would like an uninitialized array. See alsoundef
, an alias forUndefInitializer()
.
Examples
julia> Array{Float64, 1}(UndefInitializer(), 3)3-element Array{Float64, 1}: 2.2752528595e-314 2.202942107e-314 2.275252907e-314
Core.undef
—Constantundef
Alias forUndefInitializer()
, which constructs an instance of the singleton typeUndefInitializer
, used in array initialization to indicate the array-constructor-caller would like an uninitialized array.
Examples
julia> Array{Float64, 1}(undef, 3)3-element Vector{Float64}: 2.2752528595e-314 2.202942107e-314 2.275252907e-314
Base.Vector
—TypeVector{T} <: AbstractVector{T}
One-dimensional dense array with elements of typeT
, often used to represent a mathematical vector. Alias forArray{T,1}
.
Base.Vector
—MethodVector{T}(undef, n)
Construct an uninitializedVector{T}
of lengthn
.
Examples
julia> Vector{Float64}(undef, 3)3-element Array{Float64, 1}: 6.90966e-310 6.90966e-310 6.90966e-310
Base.Vector
—MethodVector{T}(nothing, m)
Construct aVector{T}
of lengthm
, initialized withnothing
entries. Element typeT
must be able to hold these values, i.e.Nothing <: T
.
Examples
julia> Vector{Union{Nothing, String}}(nothing, 2)2-element Vector{Union{Nothing, String}}: nothing nothing
Base.Vector
—MethodVector{T}(missing, m)
Construct aVector{T}
of lengthm
, initialized withmissing
entries. Element typeT
must be able to hold these values, i.e.Missing <: T
.
Examples
julia> Vector{Union{Missing, String}}(missing, 2)2-element Vector{Union{Missing, String}}: missing missing
Base.Matrix
—TypeMatrix{T} <: AbstractMatrix{T}
Two-dimensional dense array with elements of typeT
, often used to represent a mathematical matrix. Alias forArray{T,2}
.
Base.Matrix
—MethodMatrix{T}(undef, m, n)
Construct an uninitializedMatrix{T}
of sizem
×n
.
Examples
julia> Matrix{Float64}(undef, 2, 3)2×3 Array{Float64, 2}: 2.36365e-314 2.28473e-314 5.0e-324 2.26704e-314 2.26711e-314 NaNjulia> similar(ans, Int32, 2, 2)2×2 Matrix{Int32}: 490537216 1277177453 1 1936748399
Base.Matrix
—MethodMatrix{T}(nothing, m, n)
Construct aMatrix{T}
of sizem
×n
, initialized withnothing
entries. Element typeT
must be able to hold these values, i.e.Nothing <: T
.
Examples
julia> Matrix{Union{Nothing, String}}(nothing, 2, 3)2×3 Matrix{Union{Nothing, String}}: nothing nothing nothing nothing nothing nothing
Base.Matrix
—MethodMatrix{T}(missing, m, n)
Construct aMatrix{T}
of sizem
×n
, initialized withmissing
entries. Element typeT
must be able to hold these values, i.e.Missing <: T
.
Examples
julia> Matrix{Union{Missing, String}}(missing, 2, 3)2×3 Matrix{Union{Missing, String}}: missing missing missing missing missing missing
Base.VecOrMat
—TypeVecOrMat{T}
Union type ofVector{T}
andMatrix{T}
which allows functions to accept either a Matrix or a Vector.
Examples
julia> Vector{Float64} <: VecOrMat{Float64}truejulia> Matrix{Float64} <: VecOrMat{Float64}truejulia> Array{Float64, 3} <: VecOrMat{Float64}false
Core.DenseArray
—TypeDenseArray{T, N} <: AbstractArray{T,N}
N
-dimensional dense array with elements of typeT
. The elements of a dense array are stored contiguously in memory.
Base.DenseVector
—TypeDenseVector{T}
One-dimensionalDenseArray
with elements of typeT
. Alias forDenseArray{T,1}
.
Base.DenseMatrix
—TypeDenseMatrix{T}
Two-dimensionalDenseArray
with elements of typeT
. Alias forDenseArray{T,2}
.
Base.DenseVecOrMat
—TypeDenseVecOrMat{T}
Union type ofDenseVector{T}
andDenseMatrix{T}
.
Base.StridedArray
—TypeStridedArray{T, N}
A hard-codedUnion
of common array types that follow thestrided array interface, with elements of typeT
andN
dimensions.
IfA
is aStridedArray
, 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. IncrementingA
along dimensiond
jumps in memory by [stride(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.
Base.StridedVector
—TypeStridedVector{T}
One dimensionalStridedArray
with elements of typeT
.
Base.StridedMatrix
—TypeStridedMatrix{T}
Two dimensionalStridedArray
with elements of typeT
.
Base.StridedVecOrMat
—TypeStridedVecOrMat{T}
Union type ofStridedVector
andStridedMatrix
with elements of typeT
.
Core.GenericMemory
—TypeGenericMemory{kind::Symbol, T, addrspace=Core.CPU} <: DenseVector{T}
Fixed-sizeDenseVector{T}
.
kind
can currently be either:not_atomic
or:atomic
. For details on what:atomic
implies, seeAtomicMemory
addrspace
can currently only be set to Core.CPU. It is designed to to permit extension by other systems such as GPUs, which might define values such as:
module CUDAconst Generic = bitcast(Core.AddrSpace{CUDA}, 0)const Global = bitcast(Core.AddrSpace{CUDA}, 1)end
The exact semantics of these other addrspaces is defined by the specific backend, but will error if the user is attempting to access these on the CPU.
This type requires Julia 1.11 or later.
Core.Memory
—TypeMemory{T} == GenericMemory{:not_atomic, T, Core.CPU}
Fixed-sizeDenseVector{T}
.
This type requires Julia 1.11 or later.
Core.memoryref
—Function`memoryref(::GenericMemory)`
Construct aGenericMemoryRef
from a memory object. This does not fail, but the resulting memory will point out-of-bounds if and only if the memory is empty.
memoryref(::GenericMemory, index::Integer)memoryref(::GenericMemoryRef, index::Integer)
Construct aGenericMemoryRef
from a memory object and an offset index (1-based) which can also be negative. This always returns an inbounds object, and will throw an error if that is not possible (because the index would result in a shift out-of-bounds of the underlying memory).
Base.Slices
—TypeSlices{P,SM,AX,S,N} <: AbstractSlices{S,N}
AnAbstractArray
of slices into a parent array over specified dimension(s), returning views that select all the data from the other dimension(s).
These should typically be constructed byeachslice
,eachcol
oreachrow
.
parent(s::Slices)
will return the parent array.
Base.RowSlices
—TypeRowSlices{M,AX,S}
A special case ofSlices
that is a vector of row slices of a matrix, as constructed byeachrow
.
parent
can be used to get the underlying matrix.
Base.ColumnSlices
—TypeColumnSlices{M,AX,S}
A special case ofSlices
that is a vector of column slices of a matrix, as constructed byeachcol
.
parent
can be used to get the underlying matrix.
Base.getindex
—Methodgetindex(type[, elements...])
Construct a 1-d array of the specified type. This is usually called with the syntaxType[]
. Element values can be specified usingType[a,b,c,...]
.
Examples
julia> Int8[1, 2, 3]3-element Vector{Int8}: 1 2 3julia> getindex(Int8, 1, 2, 3)3-element Vector{Int8}: 1 2 3
Base.zeros
—Functionzeros([T=Float64,] dims::Tuple)zeros([T=Float64,] dims...)
Create anArray
, with element typeT
, of all zeros with size specified bydims
. See alsofill
,ones
,zero
.
Examples
julia> zeros(1)1-element Vector{Float64}: 0.0julia> zeros(Int8, 2, 3)2×3 Matrix{Int8}: 0 0 0 0 0 0
Base.ones
—Functionones([T=Float64,] dims::Tuple)ones([T=Float64,] dims...)
Create anArray
, with element typeT
, of all ones with size specified bydims
. See alsofill
,zeros
.
Examples
julia> ones(1,2)1×2 Matrix{Float64}: 1.0 1.0julia> ones(ComplexF64, 2, 3)2×3 Matrix{ComplexF64}: 1.0+0.0im 1.0+0.0im 1.0+0.0im 1.0+0.0im 1.0+0.0im 1.0+0.0im
Base.BitArray
—TypeBitArray{N} <: AbstractArray{Bool, N}
Space-efficientN
-dimensional boolean array, using just one bit for each boolean value.
BitArray
s pack up to 64 values into every 8 bytes, resulting in an 8x space efficiency overArray{Bool, N}
and allowing some operations to work on 64 values at once.
By default, Julia returnsBitArrays
frombroadcasting operations that generate boolean elements (including dotted-comparisons like.==
) as well as from the functionstrues
andfalses
.
Due to its packed storage format, concurrent access to the elements of aBitArray
where at least one of them is a write is not thread-safe.
Base.BitArray
—MethodBitArray(undef, dims::Integer...)BitArray{N}(undef, dims::NTuple{N,Int})
Construct an undefBitArray
with the given dimensions. Behaves identically to theArray
constructor. Seeundef
.
Examples
julia> BitArray(undef, 2, 2)2×2 BitMatrix: 0 0 0 0julia> BitArray(undef, (3, 1))3×1 BitMatrix: 0 0 0
Base.BitArray
—MethodBitArray(itr)
Construct aBitArray
generated by the given iterable object. The shape is inferred from theitr
object.
Examples
julia> BitArray([1 0; 0 1])2×2 BitMatrix: 1 0 0 1julia> BitArray(x+y == 3 for x = 1:2, y = 1:3)2×3 BitMatrix: 0 1 0 1 0 0julia> BitArray(x+y == 3 for x = 1:2 for y = 1:3)6-element BitVector: 0 1 0 1 0 0
Base.trues
—Functiontrues(dims)
Create aBitArray
with all values set totrue
.
Examples
julia> trues(2,3)2×3 BitMatrix: 1 1 1 1 1 1
Base.falses
—Functionfalses(dims)
Create aBitArray
with all values set tofalse
.
Examples
julia> falses(2,3)2×3 BitMatrix: 0 0 0 0 0 0
Base.fill
—Functionfill(value, dims::Tuple)fill(value, dims...)
Create an array of sizedims
with every location set tovalue
.
For example,fill(1.0, (5,5))
returns a 5×5 array of floats, with1.0
in every location of the array.
The dimension lengthsdims
may be specified as either a tuple or a sequence of arguments. AnN
-length tuple orN
arguments following thevalue
specify anN
-dimensional array. Thus, a common idiom for creating a zero-dimensional array with its only location set tox
isfill(x)
.
Every location of the returned array is set to (and is thus===
to) thevalue
that was passed; this means that if thevalue
is itself modified, all elements of thefill
ed array will reflect that modification because they'restill that veryvalue
. This is of no concern withfill(1.0, (5,5))
as thevalue
1.0
is immutable and cannot itself be modified, but can be unexpected with mutable values like — most commonly — arrays. For example,fill([], 3)
placesthe very same empty array in all three locations of the returned vector:
julia> v = fill([], 3)3-element Vector{Vector{Any}}: [] [] []julia> v[1] === v[2] === v[3]truejulia> value = v[1]Any[]julia> push!(value, 867_5309)1-element Vector{Any}: 8675309julia> v3-element Vector{Vector{Any}}: [8675309] [8675309] [8675309]
To create an array of many independent inner arrays, use acomprehension instead. This creates a new and distinct array on each iteration of the loop:
julia> v2 = [[] for _ in 1:3]3-element Vector{Vector{Any}}: [] [] []julia> v2[1] === v2[2] === v2[3]falsejulia> push!(v2[1], 8675309)1-element Vector{Any}: 8675309julia> v23-element Vector{Vector{Any}}: [8675309] [] []
See also:fill!
,zeros
,ones
,similar
.
Examples
julia> fill(1.0, (2,3))2×3 Matrix{Float64}: 1.0 1.0 1.0 1.0 1.0 1.0julia> fill(42)0-dimensional Array{Int64, 0}:42julia> A = fill(zeros(2), 2) # sets both elements to the same [0.0, 0.0] vector2-element Vector{Vector{Float64}}: [0.0, 0.0] [0.0, 0.0]julia> A[1][1] = 42; # modifies the filled value to be [42.0, 0.0]julia> A # both A[1] and A[2] are the very same vector2-element Vector{Vector{Float64}}: [42.0, 0.0] [42.0, 0.0]
Base.fill!
—Functionfill!(A, x)
Fill arrayA
with the valuex
. Ifx
is an object reference, all elements will refer to the same object.fill!(A, Foo())
will returnA
filled with the result of evaluatingFoo()
once.
Examples
julia> A = zeros(2,3)2×3 Matrix{Float64}: 0.0 0.0 0.0 0.0 0.0 0.0julia> fill!(A, 2.)2×3 Matrix{Float64}: 2.0 2.0 2.0 2.0 2.0 2.0julia> a = [1, 1, 1]; A = fill!(Vector{Vector{Int}}(undef, 3), a); a[1] = 2; A3-element Vector{Vector{Int64}}: [2, 1, 1] [2, 1, 1] [2, 1, 1]julia> x = 0; f() = (global x += 1; x); fill!(Vector{Int}(undef, 3), f())3-element Vector{Int64}: 1 1 1
Base.empty
—Functionempty(x::Tuple)
Return an empty tuple,()
.
empty(v::AbstractVector, [eltype])
Create an empty vector similar tov
, optionally changing theeltype
.
See also:empty!
,isempty
,isassigned
.
Examples
julia> empty([1.0, 2.0, 3.0])Float64[]julia> empty([1.0, 2.0, 3.0], String)String[]
empty(a::AbstractDict, [index_type=keytype(a)], [value_type=valtype(a)])
Create an emptyAbstractDict
container which can accept indices of typeindex_type
and values of typevalue_type
. The second and third arguments are optional and default to the input'skeytype
andvaltype
, respectively. (If only one of the two types is specified, it is assumed to be thevalue_type
, and theindex_type
we default tokeytype(a)
).
CustomAbstractDict
subtypes may choose which specific dictionary type is best suited to return for the given index and value types, by specializing on the three-argument signature. The default is to return an emptyDict
.
Base.similar
—Functionsimilar(A::AbstractSparseMatrixCSC{Tv,Ti}, [::Type{TvNew}, ::Type{TiNew}, m::Integer, n::Integer]) where {Tv,Ti}
Create an uninitialized mutable array with the given element type, index type, and size, based upon the given sourceSparseMatrixCSC
. The new sparse matrix maintains the structure of the original sparse matrix, except in the case where dimensions of the output matrix are different from the output.
The output matrix has zeros in the same locations as the input, but uninitialized values for the nonzero locations.
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'seltype
andsize
. 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 anArray{element_type}(undef, dims...)
.
For example,similar(1:10, 1, 4)
returns an uninitializedArray{Int,2}
since ranges are neither mutable nor support 2 dimensions:
julia> similar(1:10, 1, 4)1×4 Matrix{Int64}: 4419743872 4374413872 4419743888 0
Conversely,similar(trues(10,10), 2)
returns an uninitializedBitVector
with two elements sinceBitArray
s are both mutable and can support 1-dimensional arrays:
julia> similar(trues(10,10), 2)2-element BitVector: 0 0
SinceBitArray
s can only store elements of typeBool
, however, if you request a different element type it will create a regularArray
instead:
julia> similar(falses(10), Float64, 2, 4)2×4 Matrix{Float64}: 2.18425e-314 2.18425e-314 2.18425e-314 2.18425e-314 2.18425e-314 2.18425e-314 2.18425e-314 2.18425e-314
See also:undef
,isassigned
.
similar(storagetype, axes)
Create an uninitialized mutable array analogous to that specified bystoragetype
, but withaxes
specified by the last argument.
Examples:
similar(Array{Int}, axes(A))
creates an array that "acts like" anArray{Int}
(and might indeed be backed by one), but which is indexed identically toA
. IfA
has conventional indexing, this will be identical toArray{Int}(undef, size(A))
, but ifA
has unconventional indexing then the indices of the result will matchA
.
similar(BitArray, (axes(A, 2),))
would create a 1-dimensional logical array whose indices match those of the columns ofA
.
Base.ndims
—Functionndims(A::AbstractArray) -> Integer
Return the number of dimensions ofA
.
Examples
julia> A = fill(1, (3,4,5));julia> ndims(A)3
Base.size
—Functionsize(A::AbstractArray, [dim])
Return a tuple containing the dimensions ofA
. Optionally you can specify a dimension to just get the length of that dimension.
Note thatsize
may not be defined for arrays with non-standard indices, in which caseaxes
may be useful. See the manual chapter onarrays with custom indices.
See also:length
,ndims
,eachindex
,sizeof
.
Examples
julia> A = fill(1, (2,3,4));julia> size(A)(2, 3, 4)julia> size(A, 2)3
Base.axes
—Methodaxes(A)
Return the tuple of valid indices for arrayA
.
Examples
julia> A = fill(1, (5,6,7));julia> axes(A)(Base.OneTo(5), Base.OneTo(6), Base.OneTo(7))
Base.axes
—Methodaxes(A, d)
Return the valid range of indices for arrayA
along dimensiond
.
See alsosize
, and the manual chapter onarrays with custom indices.
Examples
julia> A = fill(1, (5,6,7));julia> axes(A, 2)Base.OneTo(6)julia> axes(A, 4) == 1:1 # all dimensions d > ndims(A) have size 1true
Usage note
Each of the indices has to be anAbstractUnitRange{<:Integer}
, but at the same time can be a type that uses custom indices. So, for example, if you need a subset, use generalized indexing constructs likebegin
/end
orfirstindex
/lastindex
:
ix = axes(v, 1)ix[2:end] # will work for eg Vector, but may fail in generalix[(begin+1):end] # works for generalized indexes
Base.length
—Methodlength(A::AbstractArray)
Return the number of elements in the array, defaults toprod(size(A))
.
Examples
julia> length([1, 2, 3, 4])4julia> length([1 2; 3 4])4
Base.keys
—Methodkeys(a::AbstractArray)
Return an efficient array describing all valid indices fora
arranged in the shape ofa
itself.
The keys of 1-dimensional arrays (vectors) are integers, whereas all other N-dimensional arrays useCartesianIndex
to describe their locations. Often the special array typesLinearIndices
andCartesianIndices
are used to efficiently represent these arrays of integers andCartesianIndex
es, respectively.
Note that thekeys
of an array might not be the most efficient index type; for maximum performance useeachindex
instead.
Examples
julia> keys([4, 5, 6])3-element LinearIndices{1, Tuple{Base.OneTo{Int64}}}: 1 2 3julia> keys([4 5; 6 7])CartesianIndices((2, 2))
Base.eachindex
—Functioneachindex(A...)eachindex(::IndexStyle, A::AbstractArray...)
Create an iterable object for visiting each index of anAbstractArray
A
in an efficient manner. For array types that have opted into fast linear indexing (likeArray
), this is simply the range1:length(A)
if they use 1-based indexing. For array types that have not opted into fast linear indexing, a specialized Cartesian range is typically returned to efficiently index into the array with indices specified for every dimension.
In generaleachindex
accepts arbitrary iterables, including strings and dictionaries, and returns an iterator object supporting arbitrary index types (e.g. unevenly spaced or non-integer indices).
IfA
isAbstractArray
it is possible to explicitly specify the style of the indices that should be returned byeachindex
by passing a value havingIndexStyle
type as its first argument (typicallyIndexLinear()
if linear indices are required orIndexCartesian()
if Cartesian range is wanted).
If you supply more than oneAbstractArray
argument,eachindex
will create an iterable object that is fast for all arguments (typically aUnitRange
if all inputs have fast linear indexing, aCartesianIndices
otherwise). If the arrays have different sizes and/or dimensionalities, aDimensionMismatch
exception will be thrown.
See alsopairs
(A)
to iterate over indices and values together, andaxes
(A, 2)
for valid indices along one dimension.
Examples
julia> A = [10 20; 30 40];julia> for i in eachindex(A) # linear indexing println("A[", i, "] == ", A[i]) endA[1] == 10A[2] == 30A[3] == 20A[4] == 40julia> for i in eachindex(view(A, 1:2, 1:1)) # Cartesian indexing println(i) endCartesianIndex(1, 1)CartesianIndex(2, 1)
Base.IndexStyle
—TypeIndexStyle(A)IndexStyle(typeof(A))
IndexStyle
specifies the "native indexing style" for arrayA
. When you define a newAbstractArray
type, you can choose to implement either linear indexing (withIndexLinear
) or cartesian indexing. If you decide to only implement linear indexing, then you must set this trait for your array type:
Base.IndexStyle(::Type{<:MyArray}) = IndexLinear()
The default isIndexCartesian()
.
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 yourAbstractArray
, 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.
Base.IndexLinear
—TypeIndexLinear()
Subtype ofIndexStyle
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 requestingeachindex
from an array that isIndexLinear
will return a simple one-dimensional range, even if it is multidimensional.
A custom array that reports itsIndexStyle
asIndexLinear
only needs to implement indexing (and indexed assignment) with a singleInt
index; all other indexing expressions — including multidimensional accesses — will be recomputed to the linear index. For example, ifA
were a2×3
custom matrix with linear indexing, and we referencedA[1, 3]
, this would be recomputed to the equivalent linear index and callA[5]
since1 + 2*(3 - 1) = 5
.
See alsoIndexCartesian
.
Base.IndexCartesian
—TypeIndexCartesian()
Subtype ofIndexStyle
used to describe arrays which are optimally indexed by a Cartesian index. This is the default for new customAbstractArray
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 requestingeachindex
from an array that isIndexCartesian
will return a range ofCartesianIndices
.
AN
-dimensional custom array that reports itsIndexStyle
asIndexCartesian
needs to implement indexing (and indexed assignment) with exactlyN
Int
indices; all other indexing expressions — including linear indexing — will be recomputed to the equivalent Cartesian location. For example, ifA
were a2×3
custom matrix with cartesian indexing, and we referencedA[5]
, this would be recomputed to the equivalent Cartesian index and callA[1, 3]
since5 = 1 + 2*(3 - 1)
.
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 anIndexCartesian
array than it is to use Cartesian indexing with anIndexLinear
array.
See alsoIndexLinear
.
Base.conj!
—Functionconj!(A)
Transform an array to its complex conjugate in-place.
See alsoconj
.
Examples
julia> A = [1+im 2-im; 2+2im 3+im]2×2 Matrix{Complex{Int64}}: 1+1im 2-1im 2+2im 3+1imjulia> conj!(A);julia> A2×2 Matrix{Complex{Int64}}: 1-1im 2+1im 2-2im 3-1im
Base.stride
—Functionstride(A, k::Integer)
Return the distance in memory (in number of elements) between adjacent elements in dimensionk
.
See also:strides
.
Examples
julia> A = fill(1, (3,4,5));julia> stride(A,2)3julia> stride(A,3)12
Base.strides
—Functionstrides(A)
Return a tuple of the memory strides in each dimension.
See also:stride
.
Examples
julia> A = fill(1, (3,4,5));julia> strides(A)(1, 3, 12)
See also thedot syntax for vectorizing functions; for example,f.(args...)
implicitly callsbroadcast(f, args...)
. Rather than relying on "vectorized" methods of functions likesin
to operate on arrays, you should usesin.(a)
to vectorize viabroadcast
.
Base.Broadcast.broadcast
—Functionbroadcast(f, As...)
Broadcast the functionf
over the arrays, tuples, collections,Ref
s and/or scalarsAs
.
Broadcasting applies the functionf
over the elements of the container arguments and the scalars themselves inAs
. 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, includingNumber
s,String
s,Symbol
s,Type
s,Function
s and some common singletons likemissing
andnothing
. All other arguments are iterated over or indexed into elementwise.
The resulting container type is established by the following rules:
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 tobroadcast(f, args...)
, and nestedf.(g.(args...))
calls are fused into a single broadcast loop.
Examples
julia> A = [1, 2, 3, 4, 5]5-element Vector{Int64}: 1 2 3 4 5julia> B = [1 2; 3 4; 5 6; 7 8; 9 10]5×2 Matrix{Int64}: 1 2 3 4 5 6 7 8 9 10julia> broadcast(+, A, B)5×2 Matrix{Int64}: 2 3 5 6 8 9 11 12 14 15julia> parse.(Int, ["1", "2"])2-element Vector{Int64}: 1 2julia> abs.((1, -2))(1, 2)julia> broadcast(+, 1.0, (0, -2.0))(1.0, -1.0)julia> (+).([[0,2], [1,3]], Ref{Vector{Int}}([1,-1]))2-element Vector{Vector{Int64}}: [1, 1] [2, 2]julia> string.(("one","two","three","four"), ": ", 1:4)4-element Vector{String}: "one: 1" "two: 2" "three: 3" "four: 4"
Base.Broadcast.broadcast!
—Functionbroadcast!(f, dest, As...)
Likebroadcast
, but store the result ofbroadcast(f, As...)
in thedest
array. Note thatdest
is only used to store the result, and does not supply arguments tof
unless it is also listed in theAs
, as inbroadcast!(f, A, A, B)
to performA[:] = broadcast(f, A, B)
.
Examples
julia> A = [1.0; 0.0]; B = [0.0; 0.0];julia> broadcast!(+, B, A, (0, -2.0));julia> B2-element Vector{Float64}: 1.0 -2.0julia> A2-element Vector{Float64}: 1.0 0.0julia> broadcast!(+, A, A, (0, -2.0));julia> A2-element Vector{Float64}: 1.0 -2.0
Base.Broadcast.@__dot__
—Macro@. expr
Convert every function call or operator inexpr
into a "dot call" (e.g. convertf(x)
tof.(x)
), and convert every assignment inexpr
to a "dot assignment" (e.g. convert+=
to.+=
).
If you want toavoid adding dots for selected function calls inexpr
, splice those function calls in with$
. For example,@. sqrt(abs($sort(x)))
is equivalent tosqrt.(abs.(sort(x)))
(no dot forsort
).
(@.
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 Vector{Float64}: 3.5244129544236893 4.727892280477045 3.4233600241796016
For specializing broadcast on custom types, see
Base.Broadcast.BroadcastStyle
—TypeBroadcastStyle
is an abstract type and trait-function used to determine behavior of objects under broadcasting.BroadcastStyle(typeof(x))
returns the style associated withx
. To customize the broadcasting behavior of a type, one can declare a style by defining a type/method pair
struct MyContainerStyle <: BroadcastStyle endBase.BroadcastStyle(::Type{<:MyContainer}) = MyContainerStyle()
One then writes method(s) (at leastsimilar
) operating onBroadcasted{MyContainerStyle}
. There are also several pre-defined subtypes ofBroadcastStyle
that you may be able to leverage; see theInterfaces chapter for more information.
Base.Broadcast.AbstractArrayStyle
—TypeBroadcast.AbstractArrayStyle{N} <: BroadcastStyle
is the abstract supertype for any style associated with anAbstractArray
type. TheN
parameter is the dimensionality, which can be handy for AbstractArray types that only support specific dimensionalities:
struct SparseMatrixStyle <: Broadcast.AbstractArrayStyle{2} endBase.BroadcastStyle(::Type{<:SparseMatrixCSC}) = SparseMatrixStyle()
ForAbstractArray
types that support arbitrary dimensionality,N
can be set toAny
:
struct MyArrayStyle <: Broadcast.AbstractArrayStyle{Any} endBase.BroadcastStyle(::Type{<:MyArray}) = MyArrayStyle()
In cases where you want to be able to mix multipleAbstractArrayStyle
s and keep track of dimensionality, your style needs to support aVal
constructor:
struct MyArrayStyleDim{N} <: Broadcast.AbstractArrayStyle{N} end(::Type{<:MyArrayStyleDim})(::Val{N}) where N = MyArrayStyleDim{N}()
Note that if two or moreAbstractArrayStyle
subtypes conflict, broadcasting machinery will fall back to producingArray
s. If this is undesirable, you may need to define binaryBroadcastStyle
rules to control the output type.
See alsoBroadcast.DefaultArrayStyle
.
Base.Broadcast.ArrayStyle
—TypeBroadcast.ArrayStyle{MyArrayType}()
is aBroadcastStyle
indicating that an object behaves as an array for broadcasting. It presents a simple way to constructBroadcast.AbstractArrayStyle
s for specificAbstractArray
container types. Broadcast styles created this way lose track of dimensionality; if keeping track is important for your type, you should create your own customBroadcast.AbstractArrayStyle
.
Base.Broadcast.DefaultArrayStyle
—TypeBroadcast.DefaultArrayStyle{N}()
is aBroadcastStyle
indicating that an object behaves as anN
-dimensional array for broadcasting. Specifically,DefaultArrayStyle
is used for anyAbstractArray
type that hasn't defined a specialized style, and in the absence of overrides from otherbroadcast
arguments the resulting output type isArray
. When there are multiple inputs tobroadcast
,DefaultArrayStyle
"loses" to any otherBroadcast.ArrayStyle
.
Base.Broadcast.broadcastable
—FunctionBroadcast.broadcastable(x)
Return eitherx
or an object likex
such that it supportsaxes
, indexing, and its type supportsndims
.
Ifx
supports iteration, the returned value should have the sameaxes
and indexing behaviors ascollect(x)
.
Ifx
is not anAbstractArray
but it supportsaxes
, indexing, and its type supportsndims
, thenbroadcastable(::typeof(x))
may be implemented to just return itself. Further, ifx
defines its ownBroadcastStyle
, then it must define itsbroadcastable
method to return itself for the custom style to have any effect.
Examples
julia> Broadcast.broadcastable([1,2,3]) # like `identity` since arrays already support axes and indexing3-element Vector{Int64}: 1 2 3julia> Broadcast.broadcastable(Int) # Types don't support axes, indexing, or iteration but are commonly used as scalarsBase.RefValue{Type{Int64}}(Int64)julia> Broadcast.broadcastable("hello") # Strings break convention of matching iteration and act like a scalar insteadBase.RefValue{String}("hello")
Base.Broadcast.combine_axes
—Functioncombine_axes(As...) -> Tuple
Determine the result axes for broadcasting across all values inAs
.
julia> Broadcast.combine_axes([1], [1 2; 3 4; 5 6])(Base.OneTo(3), Base.OneTo(2))julia> Broadcast.combine_axes(1, 1, 1)()
Base.Broadcast.combine_styles
—Functioncombine_styles(cs...) -> BroadcastStyle
Decides whichBroadcastStyle
to use for any number of value arguments. UsesBroadcastStyle
to get the style for each argument, and usesresult_style
to combine styles.
Examples
julia> Broadcast.combine_styles([1], [1 2; 3 4])Base.Broadcast.DefaultArrayStyle{2}()
Base.Broadcast.result_style
—Functionresult_style(s1::BroadcastStyle[, s2::BroadcastStyle]) -> BroadcastStyle
Takes one or twoBroadcastStyle
s and combines them usingBroadcastStyle
to determine a commonBroadcastStyle
.
Examples
julia> Broadcast.result_style(Broadcast.DefaultArrayStyle{0}(), Broadcast.DefaultArrayStyle{3}())Base.Broadcast.DefaultArrayStyle{3}()julia> Broadcast.result_style(Broadcast.Unknown(), Broadcast.DefaultArrayStyle{1}())Base.Broadcast.DefaultArrayStyle{1}()
Base.getindex
—Methodgetindex(A, inds...)
Return a subset of arrayA
as selected by the indicesinds
.
Each index may be anysupported index type, such as anInteger
,CartesianIndex
,range, orarray of supported indices. A: may be used to select all elements along a specific dimension, and a boolean array (e.g. anArray{Bool}
or aBitArray
) may be used to filter for elements where the corresponding index istrue
.
Wheninds
selects multiple elements, this function returns a newly allocated array. To index multiple elements without making a copy, useview
instead.
See the manual section onarray indexing for details.
Examples
julia> A = [1 2; 3 4]2×2 Matrix{Int64}: 1 2 3 4julia> getindex(A, 1)1julia> getindex(A, [2, 1])2-element Vector{Int64}: 3 1julia> getindex(A, 2:4)3-element Vector{Int64}: 3 2 4julia> getindex(A, 2, 1)3julia> getindex(A, CartesianIndex(2, 1))3julia> getindex(A, :, 2)2-element Vector{Int64}: 2 4julia> getindex(A, 2, :)2-element Vector{Int64}: 3 4julia> getindex(A, A .> 2)2-element Vector{Int64}: 3 4
Base.setindex!
—Methodsetindex!(A, X, inds...)A[inds...] = X
Store values from arrayX
within some subset ofA
as specified byinds
. The syntaxA[inds...] = X
is equivalent to(setindex!(A, X, inds...); X)
.
Behavior can be unexpected when any mutated argument shares memory with any other argument.
Examples
julia> A = zeros(2,2);julia> setindex!(A, [10, 20], [1, 2]);julia> A[[3, 4]] = [30, 40];julia> A2×2 Matrix{Float64}: 10.0 30.0 20.0 40.0
Base.nextind
—Functionnextind(A, i)
Return the index afteri
inA
. The returned index is often equivalent toi + 1
for an integeri
. This function can be useful for generic code.
The returned index might be out of bounds. Consider usingcheckbounds
.
See also:prevind
.
Examples
julia> x = [1 2; 3 4]2×2 Matrix{Int64}: 1 2 3 4julia> nextind(x, 1) # valid result2julia> nextind(x, 4) # invalid result5julia> nextind(x, CartesianIndex(1, 1)) # valid resultCartesianIndex(2, 1)julia> nextind(x, CartesianIndex(2, 2)) # invalid resultCartesianIndex(1, 3)
Base.prevind
—Functionprevind(A, i)
Return the index beforei
inA
. The returned index is often equivalent toi - 1
for an integeri
. This function can be useful for generic code.
The returned index might be out of bounds. Consider usingcheckbounds
.
See also:nextind
.
Examples
julia> x = [1 2; 3 4]2×2 Matrix{Int64}: 1 2 3 4julia> prevind(x, 4) # valid result3julia> prevind(x, 1) # invalid result0julia> prevind(x, CartesianIndex(2, 2)) # valid resultCartesianIndex(1, 2)julia> prevind(x, CartesianIndex(1, 1)) # invalid resultCartesianIndex(2, 0)
Base.copyto!
—Methodcopyto!(dest, Rdest::CartesianIndices, src, Rsrc::CartesianIndices) -> dest
Copy the block ofsrc
in the range ofRsrc
to the block ofdest
in the range ofRdest
. The sizes of the two regions must match.
Examples
julia> A = zeros(5, 5);julia> B = [1 2; 3 4];julia> Ainds = CartesianIndices((2:3, 2:3));julia> Binds = CartesianIndices(B);julia> copyto!(A, Ainds, B, Binds)5×5 Matrix{Float64}: 0.0 0.0 0.0 0.0 0.0 0.0 1.0 2.0 0.0 0.0 0.0 3.0 4.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0
Base.copy!
—Functioncopy!(dst, src) -> dst
In-placecopy
ofsrc
intodst
, discarding any pre-existing elements indst
. Ifdst
andsrc
are of the same type,dst == src
should hold after the call. Ifdst
andsrc
are multidimensional arrays, they must have equalaxes
.
Behavior can be unexpected when any mutated argument shares memory with any other argument.
See alsocopyto!
.
This method requires at least Julia 1.1. In Julia 1.0 this method is available from theFuture
standard library asFuture.copy!
.
Base.isassigned
—Functionisassigned(array, i) -> Bool
Test whether the given array has a value associated with indexi
. Returnfalse
if the index is out of bounds, or has an undefined reference.
Examples
julia> isassigned(rand(3, 3), 5)truejulia> isassigned(rand(3, 3), 3 * 3 + 1)falsejulia> mutable struct Foo endjulia> v = similar(rand(3), Foo)3-element Vector{Foo}: #undef #undef #undefjulia> isassigned(v, 1)false
Base.Colon
—TypeColon()
Colons (:) are used to signify indexing entire objects or dimensions at once.
Very few operations are defined on Colons directly; instead they are converted byto_indices
to an internal vector type (Base.Slice
) to represent the collection of indices they span before being used.
The singleton instance ofColon
is also a function used to construct ranges; see:
.
Base.IteratorsMD.CartesianIndex
—TypeCartesianIndex(i, j, k...) -> ICartesianIndex((i, j, k...)) -> I
Create a multidimensional indexI
, which can be used for indexing a multidimensional arrayA
. In particular,A[I]
is equivalent toA[i,j,k...]
. One can freely mix integer andCartesianIndex
indices; for example,A[Ipre, i, Ipost]
(whereIpre
andIpost
areCartesianIndex
indices andi
is anInt
) can be a useful expression when writing algorithms that work along a single dimension of an array of arbitrary dimensionality.
ACartesianIndex
is sometimes produced byeachindex
, and always when iterating with an explicitCartesianIndices
.
AnI::CartesianIndex
is treated as a "scalar" (not a container) forbroadcast
. In order to iterate over the components of aCartesianIndex
, convert it to a tuple withTuple(I)
.
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 16julia> A[CartesianIndex((1, 1, 1, 1))]1julia> A[CartesianIndex((1, 1, 1, 2))]9julia> A[CartesianIndex((1, 1, 2, 1))]5
Using aCartesianIndex
as a "scalar" forbroadcast
requires Julia 1.10; in previous releases, useRef(I)
.
Base.IteratorsMD.CartesianIndices
—TypeCartesianIndices(sz::Dims) -> RCartesianIndices((istart:[istep:]istop, jstart:[jstep:]jstop, ...)) -> R
Define a regionR
spanning a multidimensional rectangular range of integer indices. These are most commonly encountered in the context of iteration, wherefor I in R ... end
will returnCartesianIndex
indicesI
equivalent to the nested loops
for j = jstart:jstep:jstop for i = istart:istep:istop ... endend
Consequently these can be useful for writing algorithms that work in arbitrary dimensions.
CartesianIndices(A::AbstractArray) -> R
As a convenience, constructing aCartesianIndices
from an array makes a range of its indices.
The step range methodCartesianIndices((istart:istep:istop, jstart:[jstep:]jstop, ...))
requires at least Julia 1.6.
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)))CartesianIndices((2, 3))
Conversion between linear and cartesian indices
Linear index to cartesian index conversion exploits the fact that aCartesianIndices
is anAbstractArray
and can be indexed linearly:
julia> cartesian = CartesianIndices((1:3, 1:2))CartesianIndices((1:3, 1:2))julia> cartesian[4]CartesianIndex(1, 2)julia> cartesian = CartesianIndices((1:2:5, 1:2))CartesianIndices((1:2:5, 1:2))julia> cartesian[2, 2]CartesianIndex(3, 2)
Broadcasting
CartesianIndices
support broadcasting arithmetic (+ and -) with aCartesianIndex
.
Broadcasting of CartesianIndices requires at least Julia 1.1.
julia> CIs = CartesianIndices((2:3, 5:6))CartesianIndices((2:3, 5:6))julia> CI = CartesianIndex(3, 4)CartesianIndex(3, 4)julia> CIs .+ CICartesianIndices((5:6, 9:10))
For cartesian to linear index conversion, seeLinearIndices
.
Base.Dims
—TypeDims{N}
AnNTuple
ofN
Int
s used to represent the dimensions of anAbstractArray
.
Base.LinearIndices
—TypeLinearIndices(A::AbstractArray)
Return aLinearIndices
array with the same shape andaxes
asA
, holding the linear index of each entry inA
. Indexing this array with cartesian indices allows mapping them to linear indices.
For arrays with conventional indexing (indices start at 1), or any multidimensional array, linear indices range from 1 tolength(A)
. However, forAbstractVector
s linear indices areaxes(A, 1)
, and therefore do not start at 1 for vectors with unconventional indexing.
Calling this function is the "safe" way to write algorithms that exploit linear indexing.
Examples
julia> A = fill(1, (5,6,7));julia> b = LinearIndices(A);julia> extrema(b)(1, 210)
LinearIndices(inds::CartesianIndices) -> RLinearIndices(sz::Dims) -> RLinearIndices((istart:istop, jstart:jstop, ...)) -> R
Return aLinearIndices
array with the specified shape oraxes
.
Examples
The main purpose of this constructor is intuitive conversion from cartesian to linear indexing:
julia> linear = LinearIndices((1:3, 1:2))3×2 LinearIndices{2, Tuple{UnitRange{Int64}, UnitRange{Int64}}}: 1 4 2 5 3 6julia> linear[1,2]4
Base.to_indices
—Functionto_indices(A, I::Tuple)
Convert the tupleI
to a tuple of indices for use in indexing into arrayA
.
The returned tuple must only contain eitherInt
s orAbstractArray
s of scalar indices that are supported by arrayA
. 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 unexportedBase.to_index(A, i)
to process each indexi
. 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)
callsto_indices(A, axes(A), I)
, which then recursively walks through both the given tuple of indices and the dimensional indices ofA
in tandem. As such, not all index types are guaranteed to propagate toBase.to_index
.
Examples
julia> A = zeros(1,2,3,4);julia> to_indices(A, (1,1,2,2))(1, 1, 2, 2)julia> to_indices(A, (1,1,2,20)) # no bounds checking(1, 1, 2, 20)julia> to_indices(A, (CartesianIndex((1,)), 2, CartesianIndex((3,4)))) # exotic index(1, 2, 3, 4)julia> to_indices(A, ([1,1], 1:2, 3, 4))([1, 1], 1:2, 3, 4)julia> to_indices(A, (1,2)) # no shape checking(1, 2)
Base.checkbounds
—Functioncheckbounds(Bool, A, I...)
Returntrue
if the specified indicesI
are in bounds for the given arrayA
. Subtypes ofAbstractArray
should specialize this method if they need to provide custom bounds checking behaviors; however, in many cases one can rely onA
's indices andcheckindex
.
See alsocheckindex
.
Examples
julia> A = rand(3, 3);julia> checkbounds(Bool, A, 2)truejulia> checkbounds(Bool, A, 3, 4)falsejulia> checkbounds(Bool, A, 1:3)truejulia> checkbounds(Bool, A, 1:3, 2:4)false
checkbounds(A, I...)
Throw an error if the specified indicesI
are not in bounds for the given arrayA
.
Base.checkindex
—Functioncheckindex(Bool, inds::AbstractUnitRange, index)
Returntrue
if the givenindex
is within the bounds ofinds
. Custom types that would like to behave as indices for all arrays can extend this method in order to provide a specialized bounds checking implementation.
See alsocheckbounds
.
Examples
julia> checkindex(Bool, 1:20, 8)truejulia> checkindex(Bool, 1:20, 21)false
Base.elsize
—Functionelsize(type)
Compute the memory stride in bytes between consecutive elements ofeltype
stored inside the giventype
, if the array elements are stored densely with a uniform linear stride.
Examples
julia> Base.elsize(rand(Float32, 10))4
A “view” is a data structure that acts like an array (it is a subtype ofAbstractArray
), but the underlying data is actually part of another array.
For example, ifx
is an array andv = @view x[1:10]
, thenv
acts like a 10-element array, but its data is actually accessing the first 10 elements ofx
. Writing to a view, e.g.v[3] = 2
, writes directly to the underlying arrayx
(in this case modifyingx[3]
).
Slicing operations likex[1:10]
create a copy by default in Julia.@view x[1:10]
changes it to make a view. The@views
macro can be used on a whole block of code (e.g.@views function foo() .... end
or@views begin ... end
) to change all the slicing operations in that block to use views. Sometimes making a copy of the data is faster and sometimes using a view is faster, as described in theperformance tips.
Base.view
—Functionview(A, inds...)
Likegetindex
, but returns a lightweight array that lazily references (or is effectively aview into) the parent arrayA
at the given index or indicesinds
instead of eagerly extracting elements or constructing a copied subset. Callinggetindex
orsetindex!
on the returned value (often aSubArray
) computes the indices to access or modify the parent array on the fly. The behavior is undefined if the shape of the parent array is changed afterview
is called because there is no bound check for the parent array; e.g., it may cause a segmentation fault.
Some immutable parent arrays (like ranges) may choose to simply recompute a new array in some circumstances instead of returning aSubArray
if doing so is efficient and provides compatible semantics.
In Julia 1.6 or later,view
can be called on anAbstractString
, returning aSubString
.
Examples
julia> A = [1 2; 3 4]2×2 Matrix{Int64}: 1 2 3 4julia> b = view(A, :, 1)2-element view(::Matrix{Int64}, :, 1) with eltype Int64: 1 3julia> fill!(b, 0)2-element view(::Matrix{Int64}, :, 1) with eltype Int64: 0 0julia> A # Note A has changed even though we modified b2×2 Matrix{Int64}: 0 2 0 4julia> view(2:5, 2:3) # returns a range as type is immutable3:4
Base.@view
—Macro@view A[inds...]
Transform the indexing expressionA[inds...]
into the equivalentview
call.
This can only be applied directly to a single indexing expression and is particularly helpful for expressions that include the specialbegin
orend
indexing syntaxes likeA[begin, 2:end-1]
(as those are not supported by the normalview
function).
Note that@view
cannot be used as the target of a regular assignment (e.g.,@view(A[1, 2:end]) = ...
), nor would the un-decoratedindexed assignment (A[1, 2:end] = ...
) or broadcasted indexed assignment (A[1, 2:end] .= ...
) make a copy. It can be useful, however, forupdating broadcasted assignments like@view(A[1, 2:end]) .+= 1
because this is a simple syntax for@view(A[1, 2:end]) .= @view(A[1, 2:end]) + 1
, and the indexing expression on the right-hand side would otherwise make a copy without the@view
.
See also@views
to switch an entire block of code to use views for non-scalar indexing.
Usingbegin
in an indexing expression to refer to the first index requires at least Julia 1.5.
Examples
julia> A = [1 2; 3 4]2×2 Matrix{Int64}: 1 2 3 4julia> b = @view A[:, 1]2-element view(::Matrix{Int64}, :, 1) with eltype Int64: 1 3julia> fill!(b, 0)2-element view(::Matrix{Int64}, :, 1) with eltype Int64: 0 0julia> A2×2 Matrix{Int64}: 0 2 0 4
Base.@views
—Macro@views expression
Convert every array-slicing operation in the given expression (which may be abegin
/end
block, loop, function, etc.) to return a view. Scalar indices, non-array types, and explicitgetindex
calls (as opposed toarray[...]
) are unaffected.
Similarly,@views
converts string slices intoSubString
views.
The@views
macro only affectsarray[...]
expressions that appear explicitly in the givenexpression
, not array slicing that occurs in functions called by that code.
Usingbegin
in an indexing expression to refer to the first index was implemented in Julia 1.4, but was only supported by@views
starting in Julia 1.5.
Examples
julia> A = zeros(3, 3);julia> @views for row in 1:3 b = A[row, :] # b is a view, not a copy b .= row # assign every element to the row index endjulia> A3×3 Matrix{Float64}: 1.0 1.0 1.0 2.0 2.0 2.0 3.0 3.0 3.0
Base.parent
—Functionparent(A)
Return the underlying parent object of the view. This parent of objects of typesSubArray
,SubString
,ReshapedArray
orLinearAlgebra.Transpose
is what was passed as an argument toview
,reshape
,transpose
, etc. during object creation. If the input is not a wrapped object, return the input itself. If the input is wrapped multiple times, only the outermost wrapper will be removed.
Examples
julia> A = [1 2; 3 4]2×2 Matrix{Int64}: 1 2 3 4julia> V = view(A, 1:2, :)2×2 view(::Matrix{Int64}, 1:2, :) with eltype Int64: 1 2 3 4julia> parent(V)2×2 Matrix{Int64}: 1 2 3 4
Base.parentindices
—Functionparentindices(A)
Return the indices in theparent
which correspond to the viewA
.
Examples
julia> A = [1 2; 3 4];julia> V = view(A, 1, :)2-element view(::Matrix{Int64}, 1, :) with eltype Int64: 1 2julia> parentindices(V)(1, Base.Slice(Base.OneTo(2)))
Base.selectdim
—Functionselectdim(A, d::Integer, i)
Return a view of all the data ofA
where the index for dimensiond
equalsi
.
Equivalent toview(A,:,:,...,i,:,:,...)
wherei
is in positiond
.
See also:eachslice
.
Examples
julia> A = [1 2 3 4; 5 6 7 8]2×4 Matrix{Int64}: 1 2 3 4 5 6 7 8julia> selectdim(A, 2, 3)2-element view(::Matrix{Int64}, :, 3) with eltype Int64: 3 7julia> selectdim(A, 2, 3:4)2×2 view(::Matrix{Int64}, :, 3:4) with eltype Int64: 3 4 7 8
Base.reinterpret
—Functionreinterpret(::Type{Out}, x::In)
Change the type-interpretation of the binary data in the isbits valuex
to that of the isbits typeOut
. The size (ignoring padding) ofOut
has to be the same as that of the type ofx
. For example,reinterpret(Float32, UInt32(7))
interprets the 4 bytes corresponding toUInt32(7)
as aFloat32
. Note thatreinterpret(In, reinterpret(Out, x)) === x
julia> reinterpret(Float32, UInt32(7))1.0f-44julia> reinterpret(NTuple{2, UInt8}, 0x1234)(0x34, 0x12)julia> reinterpret(UInt16, (0x34, 0x12))0x1234julia> reinterpret(Tuple{UInt16, UInt8}, (0x01, 0x0203))(0x0301, 0x02)
The treatment of padding differs from reinterpret(::DataType, ::AbstractArray).
Use caution if some combinations of bits inOut
are not considered valid and would otherwise be prevented by the type's constructors and methods. Unexpected behavior may result without additional validation.
reinterpret(T::DataType, A::AbstractArray)
Construct a view of the array with the same binary data as the given array, but withT
as element type.
This function also works on "lazy" array whose elements are not computed until they are explicitly retrieved. For instance,reinterpret
on the range1:6
works similarly as on the dense vectorcollect(1:6)
:
julia> reinterpret(Float32, UInt32[1 2 3 4 5])1×5 reinterpret(Float32, ::Matrix{UInt32}): 1.0f-45 3.0f-45 4.0f-45 6.0f-45 7.0f-45julia> reinterpret(Complex{Int}, 1:6)3-element reinterpret(Complex{Int64}, ::UnitRange{Int64}): 1 + 2im 3 + 4im 5 + 6im
If the location of padding bits does not line up betweenT
andeltype(A)
, the resulting array will be read-only or write-only, to prevent invalid bits from being written to or read from, respectively.
julia> a = reinterpret(Tuple{UInt8, UInt32}, UInt32[1, 2])1-element reinterpret(Tuple{UInt8, UInt32}, ::Vector{UInt32}): (0x01, 0x00000002)julia> a[1] = 3ERROR: Padding of type Tuple{UInt8, UInt32} is not compatible with type UInt32.julia> b = reinterpret(UInt32, Tuple{UInt8, UInt32}[(0x01, 0x00000002)]); # showing will errorjulia> b[1]ERROR: Padding of type UInt32 is not compatible with type Tuple{UInt8, UInt32}.
reinterpret(reshape, T, A::AbstractArray{S}) -> B
Change the type-interpretation ofA
while consuming or adding a "channel dimension."
Ifsizeof(T) = n*sizeof(S)
forn>1
,A
's first dimension must be of sizen
andB
lacksA
's first dimension. Conversely, ifsizeof(S) = n*sizeof(T)
forn>1
,B
gets a new first dimension of sizen
. The dimensionality is unchanged ifsizeof(T) == sizeof(S)
.
This method requires at least Julia 1.6.
Examples
julia> A = [1 2; 3 4]2×2 Matrix{Int64}: 1 2 3 4julia> reinterpret(reshape, Complex{Int}, A) # the result is a vector2-element reinterpret(reshape, Complex{Int64}, ::Matrix{Int64}) with eltype Complex{Int64}: 1 + 3im 2 + 4imjulia> a = [(1,2,3), (4,5,6)]2-element Vector{Tuple{Int64, Int64, Int64}}: (1, 2, 3) (4, 5, 6)julia> reinterpret(reshape, Int, a) # the result is a matrix3×2 reinterpret(reshape, Int64, ::Vector{Tuple{Int64, Int64, Int64}}) with eltype Int64: 1 4 2 5 3 6
Base.reshape
—Functionreshape(A, dims...) -> AbstractArrayreshape(A, dims) -> AbstractArray
Return an array with the same data asA
, but with different dimension sizes or number of dimensions. The two arrays share the same underlying data, so that the result is mutable if and only ifA
is mutable, and setting elements of one alters the values of the other.
The new dimensions may be specified either as a list of arguments or as a shape tuple. At most one dimension may be specified with a:
, in which case its length is computed such that its product with all the specified dimensions is equal to the length of the original arrayA
. The total number of elements must not change.
Examples
julia> A = Vector(1:16)16-element Vector{Int64}: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16julia> reshape(A, (4, 4))4×4 Matrix{Int64}: 1 5 9 13 2 6 10 14 3 7 11 15 4 8 12 16julia> reshape(A, 2, :)2×8 Matrix{Int64}: 1 3 5 7 9 11 13 15 2 4 6 8 10 12 14 16julia> reshape(1:6, 2, 3)2×3 reshape(::UnitRange{Int64}, 2, 3) with eltype Int64: 1 3 5 2 4 6
Base.dropdims
—Functiondropdims(A; dims)
Return an array with the same data asA
, but with the dimensions specified bydims
removed.size(A,d)
must equal 1 for everyd
indims
, and repeated dimensions or numbers outside1:ndims(A)
are forbidden.
The result shares the same underlying data asA
, such that the result is mutable if and only ifA
is mutable, and setting elements of one alters the values of the other.
Examples
julia> a = reshape(Vector(1:4),(2,2,1,1))2×2×1×1 Array{Int64, 4}:[:, :, 1, 1] = 1 3 2 4julia> b = dropdims(a; dims=3)2×2×1 Array{Int64, 3}:[:, :, 1] = 1 3 2 4julia> b[1,1,1] = 5; a2×2×1×1 Array{Int64, 4}:[:, :, 1, 1] = 5 3 2 4
Base.vec
—Functionvec(a::AbstractArray) -> AbstractVector
Reshape the arraya
as a one-dimensional column vector. Returna
if it is already anAbstractVector
. The resulting array shares the same underlying data asa
, so it will only be mutable ifa
is mutable, in which case modifying one will also modify the other.
Examples
julia> a = [1 2 3; 4 5 6]2×3 Matrix{Int64}: 1 2 3 4 5 6julia> vec(a)6-element Vector{Int64}: 1 4 2 5 3 6julia> vec(1:3)1:3
Base.SubArray
—TypeSubArray{T,N,P,I,L} <: AbstractArray{T,N}
N
-dimensional view into a parent array (of typeP
) with an element typeT
, restricted by a tuple of indices (of typeI
).L
is true for types that support fast linear indexing, andfalse
otherwise.
ConstructSubArray
s using theview
function.
Base.cat
—Functioncat(A...; dims)
Concatenate the input arrays along the dimensions specified indims
.
Along a dimensiond in dims
, the size of the output array issum(size(a,d) for a in A)
. Along other dimensions, all input arrays should have the same size, which will also be the size of the output array along those dimensions.
Ifdims
is a single number, the different arrays are tightly packed along that dimension. Ifdims
is an iterable containing several dimensions, the positions along these dimensions are increased simultaneously for each input array, filling with zero elsewhere. This allows one to construct block-diagonal matrices ascat(matrices...; dims=(1,2))
, and their higher-dimensional analogues.
The special casedims=1
isvcat
, anddims=2
ishcat
. See alsohvcat
,hvncat
,stack
,repeat
.
The keyword also acceptsVal(dims)
.
For multiple dimensionsdims = Val(::Tuple)
was added in Julia 1.8.
Examples
Concatenate two arrays in different dimensions:
julia> a = [1 2 3]1×3 Matrix{Int64}: 1 2 3julia> b = [4 5 6]1×3 Matrix{Int64}: 4 5 6julia> cat(a, b; dims=1)2×3 Matrix{Int64}: 1 2 3 4 5 6julia> cat(a, b; dims=2)1×6 Matrix{Int64}: 1 2 3 4 5 6julia> cat(a, b; dims=(1, 2))2×6 Matrix{Int64}: 1 2 3 0 0 0 0 0 0 4 5 6
Extended Help
Concatenate 3D arrays:
julia> a = ones(2, 2, 3);julia> b = ones(2, 2, 4);julia> c = cat(a, b; dims=3);julia> size(c) == (2, 2, 7)true
Concatenate arrays of different sizes:
julia> cat([1 2; 3 4], [pi, pi], fill(10, 2,3,1); dims=2) # same as hcat2×6×1 Array{Float64, 3}:[:, :, 1] = 1.0 2.0 3.14159 10.0 10.0 10.0 3.0 4.0 3.14159 10.0 10.0 10.0
Construct a block diagonal matrix:
julia> cat(true, trues(2,2), trues(4)', dims=(1,2)) # block-diagonal4×7 Matrix{Bool}: 1 0 0 0 0 0 0 0 1 1 0 0 0 0 0 1 1 0 0 0 0 0 0 0 1 1 1 1
julia> cat(1, [2], [3;;]; dims=Val(2))1×3 Matrix{Int64}: 1 2 3
cat
does not join two strings, you may want to use*
.
julia> a = "aaa";julia> b = "bbb";julia> cat(a, b; dims=1)2-element Vector{String}: "aaa" "bbb"julia> cat(a, b; dims=2)1×2 Matrix{String}: "aaa" "bbb"julia> a * b"aaabbb"
Base.vcat
—Functionvcat(A...)
Concatenate arrays or numbers vertically. Equivalent tocat
(A...; dims=1)
, and to the syntax[a; b; c]
.
To concatenate a large vector of arrays,reduce(vcat, A)
calls an efficient method whenA isa AbstractVector{<:AbstractVecOrMat}
, rather than working pairwise.
See alsohcat
,Iterators.flatten
,stack
.
Examples
julia> v = vcat([1,2], [3,4])4-element Vector{Int64}: 1 2 3 4julia> v == vcat(1, 2, [3,4]) # accepts numberstruejulia> v == [1; 2; [3,4]] # syntax for the same operationtruejulia> summary(ComplexF64[1; 2; [3,4]]) # syntax for supplying the element type"4-element Vector{ComplexF64}"julia> vcat(range(1, 2, length=3)) # collects lazy ranges3-element Vector{Float64}: 1.0 1.5 2.0julia> two = ([10, 20, 30]', Float64[4 5 6; 7 8 9]) # row vector and a matrix([10 20 30], [4.0 5.0 6.0; 7.0 8.0 9.0])julia> vcat(two...)3×3 Matrix{Float64}: 10.0 20.0 30.0 4.0 5.0 6.0 7.0 8.0 9.0julia> vs = [[1, 2], [3, 4], [5, 6]];julia> reduce(vcat, vs) # more efficient than vcat(vs...)6-element Vector{Int64}: 1 2 3 4 5 6julia> ans == collect(Iterators.flatten(vs))true
Base.hcat
—Functionhcat(A...)
Concatenate arrays or numbers horizontally. Equivalent tocat
(A...; dims=2)
, and to the syntax[a b c]
or[a;; b;; c]
.
For a large vector of arrays,reduce(hcat, A)
calls an efficient method whenA isa AbstractVector{<:AbstractVecOrMat}
. For a vector of vectors, this can also be writtenstack
(A)
.
Examples
julia> hcat([1,2], [3,4], [5,6])2×3 Matrix{Int64}: 1 3 5 2 4 6julia> hcat(1, 2, [30 40], [5, 6, 7]') # accepts numbers1×7 Matrix{Int64}: 1 2 30 40 5 6 7julia> ans == [1 2 [30 40] [5, 6, 7]'] # syntax for the same operationtruejulia> Float32[1 2 [30 40] [5, 6, 7]'] # syntax for supplying the eltype1×7 Matrix{Float32}: 1.0 2.0 30.0 40.0 5.0 6.0 7.0julia> ms = [zeros(2,2), [1 2; 3 4], [50 60; 70 80]];julia> reduce(hcat, ms) # more efficient than hcat(ms...)2×6 Matrix{Float64}: 0.0 0.0 1.0 2.0 50.0 60.0 0.0 0.0 3.0 4.0 70.0 80.0julia> stack(ms) |> summary # disagrees on a vector of matrices"2×2×3 Array{Float64, 3}"julia> hcat(Int[], Int[], Int[]) # empty vectors, each of size (0,)0×3 Matrix{Int64}julia> hcat([1.1, 9.9], Matrix(undef, 2, 0)) # hcat with empty 2×0 Matrix2×1 Matrix{Any}: 1.1 9.9
Base.hvcat
—Functionhvcat(blocks_per_row::Union{Tuple{Vararg{Int}}, Int}, values...)
Horizontal and vertical concatenation in one call. This function is called for block matrix syntax. The first argument specifies the number of arguments to concatenate in each block row. If the first argument is a single integern
, then all block rows are assumed to haven
block columns.
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 Matrix{Int64}: 1 2 3 4 5 6julia> hvcat((3,3), a,b,c,d,e,f)2×3 Matrix{Int64}: 1 2 3 4 5 6julia> [a b; c d; e f]3×2 Matrix{Int64}: 1 2 3 4 5 6julia> hvcat((2,2,2), a,b,c,d,e,f)3×2 Matrix{Int64}: 1 2 3 4 5 6julia> hvcat((2,2,2), a,b,c,d,e,f) == hvcat(2, a,b,c,d,e,f)true
Base.hvncat
—Functionhvncat(dim::Int, row_first, values...)hvncat(dims::Tuple{Vararg{Int}}, row_first, values...)hvncat(shape::Tuple{Vararg{Tuple}}, row_first, values...)
Horizontal, vertical, and n-dimensional concatenation of manyvalues
in one call.
This function is called for block matrix syntax. The first argument either specifies the shape of the concatenation, similar tohvcat
, as a tuple of tuples, or the dimensions that specify the key number of elements along each axis, and is used to determine the output dimensions. Thedims
form is more performant, and is used by default when the concatenation operation has the same number of elements along each axis (e.g., [a b; c d;;; e f ; g h]). Theshape
form is used when the number of elements along each axis is unbalanced (e.g., [a b ; c]). Unbalanced syntax needs additional validation overhead. Thedim
form is an optimization for concatenation along just one dimension.row_first
indicates howvalues
are ordered. The meaning of the first and second elements ofshape
are also swapped based onrow_first
.
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]1×3×2 Array{Int64, 3}:[:, :, 1] = 1 2 3[:, :, 2] = 4 5 6julia> hvncat((2,1,3), false, a,b,c,d,e,f)2×1×3 Array{Int64, 3}:[:, :, 1] = 1 2[:, :, 2] = 3 4[:, :, 3] = 5 6julia> [a b;;; c d;;; e f]1×2×3 Array{Int64, 3}:[:, :, 1] = 1 2[:, :, 2] = 3 4[:, :, 3] = 5 6julia> hvncat(((3, 3), (3, 3), (6,)), true, a, b, c, d, e, f)1×3×2 Array{Int64, 3}:[:, :, 1] = 1 2 3[:, :, 2] = 4 5 6
Examples for construction of the arguments
[a b c ; d e f ;;; g h i ; j k l ;;; m n o ; p q r ;;; s t u ; v w x]⇒ dims = (2, 3, 4)[a b ; c ;;; d ;;;;] ___ _ _ 2 1 1 = elements in each row (2, 1, 1) _______ _ 3 1 = elements in each column (3, 1) _____________ 4 = elements in each 3d slice (4,) _____________ 4 = elements in each 4d slice (4,)⇒ shape = ((2, 1, 1), (3, 1), (4,), (4,)) with `row_first` = true
Base.stack
—Functionstack(iter; [dims])
Combine a collection of arrays (or other iterable objects) of equal size into one larger array, by arranging them along one or more new dimensions.
By default the axes of the elements are placed first, givingsize(result) = (size(first(iter))..., size(iter)...)
. This has the same order of elements asIterators.flatten
(iter)
.
With keyworddims::Integer
, instead thei
th element ofiter
becomes the sliceselectdim
(result, dims, i)
, so thatsize(result, dims) == length(iter)
. In this casestack
reverses the action ofeachslice
with the samedims
.
The variouscat
functions also combine arrays. However, these all extend the arrays' existing (possibly trivial) dimensions, rather than placing the arrays along new dimensions. They also accept arrays as separate arguments, rather than a single collection.
This function requires at least Julia 1.9.
Examples
julia> vecs = (1:2, [30, 40], Float32[500, 600]);julia> mat = stack(vecs)2×3 Matrix{Float32}: 1.0 30.0 500.0 2.0 40.0 600.0julia> mat == hcat(vecs...) == reduce(hcat, collect(vecs))truejulia> vec(mat) == vcat(vecs...) == reduce(vcat, collect(vecs))truejulia> stack(zip(1:4, 10:99)) # accepts any iterators of iterators2×4 Matrix{Int64}: 1 2 3 4 10 11 12 13julia> vec(ans) == collect(Iterators.flatten(zip(1:4, 10:99)))truejulia> stack(vecs; dims=1) # unlike any cat function, 1st axis of vecs[1] is 2nd axis of result3×2 Matrix{Float32}: 1.0 2.0 30.0 40.0 500.0 600.0julia> x = rand(3,4);julia> x == stack(eachcol(x)) == stack(eachrow(x), dims=1) # inverse of eachslicetrue
Higher-dimensional examples:
julia> A = rand(5, 7, 11);julia> E = eachslice(A, dims=2); # a vector of matricesjulia> (element = size(first(E)), container = size(E))(element = (5, 11), container = (7,))julia> stack(E) |> size(5, 11, 7)julia> stack(E) == stack(E; dims=3) == cat(E...; dims=3)truejulia> A == stack(E; dims=2)truejulia> M = (fill(10i+j, 2, 3) for i in 1:5, j in 1:7);julia> (element = size(first(M)), container = size(M))(element = (2, 3), container = (5, 7))julia> stack(M) |> size # keeps all dimensions(2, 3, 5, 7)julia> stack(M; dims=1) |> size # vec(container) along dims=1(35, 2, 3)julia> hvcat(5, M...) |> size # hvcat puts matrices next to each other(14, 15)
stack(f, args...; [dims])
Apply a function to each element of a collection, andstack
the result. Or to several collections,zip
ped together.
The function should return arrays (or tuples, or other iterators) all of the same size. These become slices of the result, each separated alongdims
(if given) or by default along the last dimensions.
Examples
julia> stack(c -> (c, c-32), "julia")2×5 Matrix{Char}: 'j' 'u' 'l' 'i' 'a' 'J' 'U' 'L' 'I' 'A'julia> stack(eachrow([1 2 3; 4 5 6]), (10, 100); dims=1) do row, n vcat(row, row .* n, row ./ n) end2×9 Matrix{Float64}: 1.0 2.0 3.0 10.0 20.0 30.0 0.1 0.2 0.3 4.0 5.0 6.0 400.0 500.0 600.0 0.04 0.05 0.06
Base.vect
—Functionvect(X...)
Create aVector
with element type computed from thepromote_typeof
of the argument, containing the argument list.
Examples
julia> a = Base.vect(UInt8(1), 2.5, 1//2)3-element Vector{Float64}: 1.0 2.5 0.5
Base.circshift
—Functioncircshift(A, shifts)
Circularly shift, i.e. rotate, the data in an array. The second argument is a tuple or vector giving the amount to shift in each dimension, or an integer to shift only in the first dimension.
See also:circshift!
,circcopy!
,bitrotate
,<<
.
Examples
julia> b = reshape(Vector(1:16), (4,4))4×4 Matrix{Int64}: 1 5 9 13 2 6 10 14 3 7 11 15 4 8 12 16julia> circshift(b, (0,2))4×4 Matrix{Int64}: 9 13 1 5 10 14 2 6 11 15 3 7 12 16 4 8julia> circshift(b, (-1,0))4×4 Matrix{Int64}: 2 6 10 14 3 7 11 15 4 8 12 16 1 5 9 13julia> a = BitArray([true, true, false, false, true])5-element BitVector: 1 1 0 0 1julia> circshift(a, 1)5-element BitVector: 1 1 1 0 0julia> circshift(a, -1)5-element BitVector: 1 0 0 1 1
Base.circshift!
—Functioncircshift!(a::AbstractVector, shift::Integer)
Circularly shift, or rotate, the data in vectora
byshift
positions.
Examples
julia> circshift!([1, 2, 3, 4, 5], 2)5-element Vector{Int64}: 4 5 1 2 3julia> circshift!([1, 2, 3, 4, 5], -2)5-element Vector{Int64}: 3 4 5 1 2
circshift!(dest, src, shifts)
Circularly shift, i.e. rotate, the data insrc
, storing the result indest
.shifts
specifies the amount to shift in each dimension.
Behavior can be unexpected when any mutated argument shares memory with any other argument.
See alsocircshift
.
Base.circcopy!
—Functioncirccopy!(dest, src)
Copysrc
todest
, indexing each dimension modulo its length.src
anddest
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 overlapdest
agrees withsrc
.
Behavior can be unexpected when any mutated argument shares memory with any other argument.
See also:circshift
.
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 16julia> dest = OffsetArray{Int}(undef, (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 3julia> dest[1:3,2:4] == src[1:3,2:4]true
Base.findall
—Methodfindall(A)
Return a vectorI
of thetrue
indices or keys ofA
. If there are no such elements ofA
, 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 bykeys(A)
andpairs(A)
.
See also:findfirst
,searchsorted
.
Examples
julia> A = [true, false, false, true]4-element Vector{Bool}: 1 0 0 1julia> findall(A)2-element Vector{Int64}: 1 4julia> A = [true false; false true]2×2 Matrix{Bool}: 1 0 0 1julia> findall(A)2-element Vector{CartesianIndex{2}}: CartesianIndex(1, 1) CartesianIndex(2, 2)julia> findall(falses(3))Int64[]
Base.findall
—Methodfindall(f::Function, A)
Return a vectorI
of the indices or keys ofA
wheref(A[I])
returnstrue
. If there are no such elements ofA
, return an empty array.
Indices or keys are of the same type as those returned bykeys(A)
andpairs(A)
.
Examples
julia> x = [1, 3, 4]3-element Vector{Int64}: 1 3 4julia> findall(isodd, x)2-element Vector{Int64}: 1 2julia> A = [1 2 0; 3 4 0]2×3 Matrix{Int64}: 1 2 0 3 4 0julia> findall(isodd, A)2-element Vector{CartesianIndex{2}}: CartesianIndex(1, 1) CartesianIndex(2, 1)julia> findall(!iszero, A)4-element Vector{CartesianIndex{2}}: 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 => 0julia> findall(x -> x >= 0, d)2-element Vector{Symbol}: :A :C
Base.findfirst
—Methodfindfirst(A)
Return the index or key of the firsttrue
value inA
. Returnnothing
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 bykeys(A)
andpairs(A)
.
See also:findall
,findnext
,findlast
,searchsortedfirst
.
Examples
julia> A = [false, false, true, false]4-element Vector{Bool}: 0 0 1 0julia> findfirst(A)3julia> findfirst(falses(3)) # returns nothing, but not printed in the REPLjulia> A = [false false; true false]2×2 Matrix{Bool}: 0 0 1 0julia> findfirst(A)CartesianIndex(2, 1)
Base.findfirst
—Methodfindfirst(predicate::Function, A)
Return the index or key of the first element ofA
for whichpredicate
returnstrue
. Returnnothing
if there is no such element.
Indices or keys are of the same type as those returned bykeys(A)
andpairs(A)
.
Examples
julia> A = [1, 4, 2, 2]4-element Vector{Int64}: 1 4 2 2julia> findfirst(iseven, A)2julia> findfirst(x -> x>10, A) # returns nothing, but not printed in the REPLjulia> findfirst(isequal(4), A)2julia> A = [1 4; 2 2]2×2 Matrix{Int64}: 1 4 2 2julia> findfirst(iseven, A)CartesianIndex(2, 1)
Base.findlast
—Methodfindlast(A)
Return the index or key of the lasttrue
value inA
. Returnnothing
if there is notrue
value inA
.
Indices or keys are of the same type as those returned bykeys(A)
andpairs(A)
.
See also:findfirst
,findprev
,findall
.
Examples
julia> A = [true, false, true, false]4-element Vector{Bool}: 1 0 1 0julia> findlast(A)3julia> A = falses(2,2);julia> findlast(A) # returns nothing, but not printed in the REPLjulia> A = [true false; true false]2×2 Matrix{Bool}: 1 0 1 0julia> findlast(A)CartesianIndex(2, 1)
Base.findlast
—Methodfindlast(predicate::Function, A)
Return the index or key of the last element ofA
for whichpredicate
returnstrue
. Returnnothing
if there is no such element.
Indices or keys are of the same type as those returned bykeys(A)
andpairs(A)
.
Examples
julia> A = [1, 2, 3, 4]4-element Vector{Int64}: 1 2 3 4julia> findlast(isodd, A)3julia> findlast(x -> x > 5, A) # returns nothing, but not printed in the REPLjulia> A = [1 2; 3 4]2×2 Matrix{Int64}: 1 2 3 4julia> findlast(isodd, A)CartesianIndex(2, 1)
Base.findnext
—Methodfindnext(A, i)
Find the next index after or includingi
of atrue
element ofA
, ornothing
if not found.
Indices are of the same type as those returned bykeys(A)
andpairs(A)
.
Examples
julia> A = [false, false, true, false]4-element Vector{Bool}: 0 0 1 0julia> findnext(A, 1)3julia> findnext(A, 4) # returns nothing, but not printed in the REPLjulia> A = [false false; true false]2×2 Matrix{Bool}: 0 0 1 0julia> findnext(A, CartesianIndex(1, 1))CartesianIndex(2, 1)
Base.findnext
—Methodfindnext(predicate::Function, A, i)
Find the next index after or includingi
of an element ofA
for whichpredicate
returnstrue
, ornothing
if not found. This works for Arrays, Strings, and most other collections that supportgetindex
,keys(A)
, andnextind
.
Indices are of the same type as those returned bykeys(A)
andpairs(A)
.
Examples
julia> A = [1, 4, 2, 2];julia> findnext(isodd, A, 1)1julia> findnext(isodd, A, 2) # returns nothing, but not printed in the REPLjulia> A = [1 4; 2 2];julia> findnext(isodd, A, CartesianIndex(1, 1))CartesianIndex(1, 1)julia> findnext(isspace, "a b c", 3)4
Base.findprev
—Methodfindprev(A, i)
Find the previous index before or includingi
of atrue
element ofA
, ornothing
if not found.
Indices are of the same type as those returned bykeys(A)
andpairs(A)
.
See also:findnext
,findfirst
,findall
.
Examples
julia> A = [false, false, true, true]4-element Vector{Bool}: 0 0 1 1julia> findprev(A, 3)3julia> findprev(A, 1) # returns nothing, but not printed in the REPLjulia> A = [false false; true true]2×2 Matrix{Bool}: 0 0 1 1julia> findprev(A, CartesianIndex(2, 1))CartesianIndex(2, 1)
Base.findprev
—Methodfindprev(predicate::Function, A, i)
Find the previous index before or includingi
of an element ofA
for whichpredicate
returnstrue
, ornothing
if not found. This works for Arrays, Strings, and most other collections that supportgetindex
,keys(A)
, andnextind
.
Indices are of the same type as those returned bykeys(A)
andpairs(A)
.
Examples
julia> A = [4, 6, 1, 2]4-element Vector{Int64}: 4 6 1 2julia> findprev(isodd, A, 1) # returns nothing, but not printed in the REPLjulia> findprev(isodd, A, 3)3julia> A = [4 6; 1 2]2×2 Matrix{Int64}: 4 6 1 2julia> findprev(isodd, A, CartesianIndex(1, 2))CartesianIndex(2, 1)julia> findprev(isspace, "a b c", 3)2
Base.permutedims
—Functionpermutedims(A::AbstractArray, perm)permutedims(A::AbstractMatrix)
Permute the dimensions (axes) of arrayA
.perm
is a tuple or vector ofndims(A)
integers specifying the permutation.
IfA
is a 2d array (AbstractMatrix
), thenperm
defaults to(2,1)
, swapping the two axes ofA
(the rows and columns of the matrix). This differs fromtranspose
in that the operation is not recursive, which is especially useful for arrays of non-numeric values (where the recursivetranspose
would throw an error) and/or 2d arrays that do not represent linear operators.
For 1d arrays, seepermutedims(v::AbstractVector)
, which returns a 1-row “matrix”.
See alsopermutedims!
,PermutedDimsArray
,transpose
,invperm
.
Examples
2d arrays:
Unliketranspose
,permutedims
can be used to swap rows and columns of 2d arrays of arbitrary non-numeric elements, such as strings:
julia> A = ["a" "b" "c" "d" "e" "f"]2×3 Matrix{String}: "a" "b" "c" "d" "e" "f"julia> permutedims(A)3×2 Matrix{String}: "a" "d" "b" "e" "c" "f"
Andpermutedims
produces results that differ fromtranspose
for matrices whose elements are themselves numeric matrices:
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 Matrix{Matrix{Int64}}: [1 2; 3 4] [5 6; 7 8] [9 10; 11 12] [13 14; 15 16]julia> permutedims(X)2×2 Matrix{Matrix{Int64}}: [1 2; 3 4] [9 10; 11 12] [5 6; 7 8] [13 14; 15 16]julia> transpose(X)2×2 transpose(::Matrix{Matrix{Int64}}) with eltype Transpose{Int64, Matrix{Int64}}: [1 3; 2 4] [9 11; 10 12] [5 7; 6 8] [13 15; 14 16]
Multi-dimensional arrays
julia> A = reshape(Vector(1:8), (2,2,2))2×2×2 Array{Int64, 3}:[:, :, 1] = 1 3 2 4[:, :, 2] = 5 7 6 8julia> perm = (3, 1, 2); # put the last dimension firstjulia> B = permutedims(A, perm)2×2×2 Array{Int64, 3}:[:, :, 1] = 1 2 5 6[:, :, 2] = 3 4 7 8julia> A == permutedims(B, invperm(perm)) # the inverse permutationtrue
For each dimensioni
ofB = permutedims(A, perm)
, its corresponding dimension ofA
will beperm[i]
. This means the equalitysize(B, i) == size(A, perm[i])
holds.
julia> A = randn(5, 7, 11, 13);julia> perm = [4, 1, 3, 2];julia> B = permutedims(A, perm);julia> size(B)(13, 5, 11, 7)julia> size(A)[perm] == anstrue
permutedims(v::AbstractVector)
Reshape vectorv
into a1 × length(v)
row matrix. Differs fromtranspose
in that the operation is not recursive, which is especially useful for arrays of non-numeric values (where the recursivetranspose
might throw an error).
Examples
Unliketranspose
,permutedims
can be used on vectors of arbitrary non-numeric elements, such as strings:
julia> permutedims(["a", "b", "c"])1×3 Matrix{String}: "a" "b" "c"
For vectors of numbers,permutedims(v)
works much liketranspose(v)
except that the return type differs (it usesreshape
rather than aLinearAlgebra.Transpose
view, though both share memory with the original arrayv
):
julia> v = [1, 2, 3, 4]4-element Vector{Int64}: 1 2 3 4julia> p = permutedims(v)1×4 Matrix{Int64}: 1 2 3 4julia> r = transpose(v)1×4 transpose(::Vector{Int64}) with eltype Int64: 1 2 3 4julia> p == rtruejulia> typeof(r)Transpose{Int64, Vector{Int64}}julia> p[1] = 5; r[2] = 6; # mutating p or r also changes vjulia> v # shares memory with both p and r4-element Vector{Int64}: 5 6 3 4
However,permutedims
produces results that differ fromtranspose
for vectors whose elements are themselves numeric matrices:
julia> V = [[[1 2; 3 4]]; [[5 6; 7 8]]]2-element Vector{Matrix{Int64}}: [1 2; 3 4] [5 6; 7 8]julia> permutedims(V)1×2 Matrix{Matrix{Int64}}: [1 2; 3 4] [5 6; 7 8]julia> transpose(V)1×2 transpose(::Vector{Matrix{Int64}}) with eltype Transpose{Int64, Matrix{Int64}}: [1 3; 2 4] [5 7; 6 8]
Base.permutedims!
—Functionpermutedims!(dest, src, perm)
Permute the dimensions of arraysrc
and store the result in the arraydest
.perm
is a vector specifying a permutation of lengthndims(src)
. The preallocated arraydest
should havesize(dest) == size(src)[perm]
and is completely overwritten. No in-place permutation is supported and unexpected results will happen ifsrc
anddest
have overlapping memory regions.
See alsopermutedims
.
Base.PermutedDimsArrays.PermutedDimsArray
—TypePermutedDimsArray(A, perm) -> B
Given an AbstractArrayA
, create a viewB
such that the dimensions appear to be permuted. Similar topermutedims
, except that no copying occurs (B
shares storage withA
).
See alsopermutedims
,invperm
.
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
Base.promote_shape
—Functionpromote_shape(s1, s2)
Check two array shapes for compatibility, allowing trailing singleton dimensions, and return whichever shape has more dimensions.
Examples
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)
Base.accumulate
—Functionaccumulate(op, A; dims::Integer, [init])
Cumulative operationop
along the dimensiondims
ofA
(providingdims
is optional for vectors). An initial valueinit
may optionally be provided by a keyword argument. See alsoaccumulate!
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 ofaccumulate
, seecumsum
,cumprod
. For a lazy version, seeIterators.accumulate
.
accumulate
on a non-array iterator requires at least Julia 1.5.
Examples
julia> accumulate(+, [1,2,3])3-element Vector{Int64}: 1 3 6julia> accumulate(min, (1, -2, 3, -4, 5), init=0)(0, -2, -2, -4, -4)julia> accumulate(/, (2, 4, Inf), init=100)(50.0, 12.5, 0.0)julia> accumulate(=>, i^2 for i in 1:3)3-element Vector{Any}: 1 1 => 4 (1 => 4) => 9julia> accumulate(+, fill(1, 3, 4))3×4 Matrix{Int64}: 1 4 7 10 2 5 8 11 3 6 9 12julia> accumulate(+, fill(1, 2, 5), dims=2, init=100.0)2×5 Matrix{Float64}: 101.0 102.0 103.0 104.0 105.0 101.0 102.0 103.0 104.0 105.0
Base.accumulate!
—Functionaccumulate!(op, B, A; [dims], [init])
Cumulative operationop
onA
along the dimensiondims
, storing the result inB
. Providingdims
is optional for vectors. If the keyword argumentinit
is given, its value is used to instantiate the accumulation.
Behavior can be unexpected when any mutated argument shares memory with any other argument.
See alsoaccumulate
,cumsum!
,cumprod!
.
Examples
julia> x = [1, 0, 2, 0, 3];julia> y = rand(5);julia> accumulate!(+, y, x);julia> y5-element Vector{Float64}: 1.0 1.0 3.0 3.0 6.0julia> A = [1 2 3; 4 5 6];julia> B = similar(A);julia> accumulate!(-, B, A, dims=1)2×3 Matrix{Int64}: 1 2 3 -3 -3 -3julia> accumulate!(*, B, A, dims=2, init=10)2×3 Matrix{Int64}: 10 20 60 40 200 1200
Base.cumprod
—Functioncumprod(A; dims::Integer)
Cumulative product along the dimensiondim
. See alsocumprod!
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 = Int8[1 2 3; 4 5 6];julia> cumprod(a, dims=1)2×3 Matrix{Int64}: 1 2 3 4 10 18julia> cumprod(a, dims=2)2×3 Matrix{Int64}: 1 2 6 4 20 120
cumprod(itr)
Cumulative product of an iterator.
See alsocumprod!
,accumulate
,cumsum
.
cumprod
on a non-array iterator requires at least Julia 1.5.
Examples
julia> cumprod(fill(1//2, 3))3-element Vector{Rational{Int64}}: 1//2 1//4 1//8julia> cumprod((1, 2, 1, 3, 1))(1, 2, 2, 6, 6)julia> cumprod("julia")5-element Vector{String}: "j" "ju" "jul" "juli" "julia"
Base.cumprod!
—Functioncumprod!(B, A; dims::Integer)
Cumulative product ofA
along the dimensiondims
, storing the result inB
. See alsocumprod
.
Behavior can be unexpected when any mutated argument shares memory with any other argument.
cumprod!(y::AbstractVector, x::AbstractVector)
Cumulative product of a vectorx
, storing the result iny
. See alsocumprod
.
Behavior can be unexpected when any mutated argument shares memory with any other argument.
Base.cumsum
—Functioncumsum(A; dims::Integer)
Cumulative sum along the dimensiondims
. See alsocumsum!
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 Matrix{Int64}: 1 2 3 4 5 6julia> cumsum(a, dims=1)2×3 Matrix{Int64}: 1 2 3 5 7 9julia> cumsum(a, dims=2)2×3 Matrix{Int64}: 1 3 6 4 9 15
The return array'seltype
isInt
for signed integers of less than system word size andUInt
for unsigned integers of less than system word size. To preserveeltype
of arrays with small signed or unsigned integeraccumulate(+, A)
should be used.
julia> cumsum(Int8[100, 28])2-element Vector{Int64}: 100 128julia> accumulate(+,Int8[100, 28])2-element Vector{Int8}: 100 -128
In the former case, the integers are widened to system word size and therefore the result isInt64[100, 128]
. In the latter case, no such widening happens and integer overflow results inInt8[100, -128]
.
cumsum(itr)
Cumulative sum of an iterator.
See alsoaccumulate
to apply functions other than+
.
cumsum
on a non-array iterator requires at least Julia 1.5.
Examples
julia> cumsum(1:3)3-element Vector{Int64}: 1 3 6julia> cumsum((true, false, true, false, true))(1, 1, 2, 2, 3)julia> cumsum(fill(1, 2) for i in 1:3)3-element Vector{Vector{Int64}}: [1, 1] [2, 2] [3, 3]
Base.cumsum!
—Functioncumsum!(B, A; dims::Integer)
Cumulative sum ofA
along the dimensiondims
, storing the result inB
. See alsocumsum
.
Behavior can be unexpected when any mutated argument shares memory with any other argument.
Base.diff
—Functiondiff(A::AbstractVector)diff(A::AbstractArray; dims::Integer)
Finite difference operator on a vector or a multidimensional arrayA
. In the latter case the dimension to operate on needs to be specified with thedims
keyword argument.
diff
for arrays with dimension higher than 2 requires at least Julia 1.1.
Examples
julia> a = [2 4; 6 16]2×2 Matrix{Int64}: 2 4 6 16julia> diff(a, dims=2)2×1 Matrix{Int64}: 2 10julia> diff(vec(a))3-element Vector{Int64}: 4 -2 12
Base.repeat
—Functionrepeat(A::AbstractArray, counts::Integer...)
Construct an array by repeating arrayA
a given number of times in each dimension, specified bycounts
.
See also:fill
,Iterators.repeated
,Iterators.cycle
.
Examples
julia> repeat([1, 2, 3], 2)6-element Vector{Int64}: 1 2 3 1 2 3julia> repeat([1, 2, 3], 2, 3)6×3 Matrix{Int64}: 1 1 1 2 2 2 3 3 3 1 1 1 2 2 2 3 3 3
repeat(A::AbstractArray; inner=ntuple(Returns(1), ndims(A)), outer=ntuple(Returns(1), ndims(A)))
Construct an array by repeating the entries ofA
. The i-th element ofinner
specifies the number of times that the individual entries of the i-th dimension ofA
should be repeated. The i-th element ofouter
specifies the number of times that a slice along the i-th dimension ofA
should be repeated. Ifinner
orouter
are omitted, no repetition is performed.
Examples
julia> repeat(1:2, inner=2)4-element Vector{Int64}: 1 1 2 2julia> repeat(1:2, outer=2)4-element Vector{Int64}: 1 2 1 2julia> repeat([1 2; 3 4], inner=(2, 1), outer=(1, 3))4×6 Matrix{Int64}: 1 2 1 2 1 2 1 2 1 2 1 2 3 4 3 4 3 4 3 4 3 4 3 4
repeat(s::AbstractString, r::Integer)
Repeat a stringr
times. This can be written ass^r
.
See also^
.
Examples
julia> repeat("ha", 3)"hahaha"
repeat(c::AbstractChar, r::Integer) -> String
Repeat a characterr
times. This can equivalently be accomplished by callingc^r
.
Examples
julia> repeat('A', 3)"AAA"
Base.rot180
—Functionrot180(A)
Rotate matrixA
180 degrees.
Examples
julia> a = [1 2; 3 4]2×2 Matrix{Int64}: 1 2 3 4julia> rot180(a)2×2 Matrix{Int64}: 4 3 2 1
rot180(A, k)
Rotate matrixA
180 degrees an integerk
number of times. Ifk
is even, this is equivalent to acopy
.
Examples
julia> a = [1 2; 3 4]2×2 Matrix{Int64}: 1 2 3 4julia> rot180(a,1)2×2 Matrix{Int64}: 4 3 2 1julia> rot180(a,2)2×2 Matrix{Int64}: 1 2 3 4
Base.rotl90
—Functionrotl90(A)
Rotate matrixA
left 90 degrees.
Examples
julia> a = [1 2; 3 4]2×2 Matrix{Int64}: 1 2 3 4julia> rotl90(a)2×2 Matrix{Int64}: 2 4 1 3
rotl90(A, k)
Left-rotate matrixA
90 degrees counterclockwise an integerk
number of times. Ifk
is a multiple of four (including zero), this is equivalent to acopy
.
Examples
julia> a = [1 2; 3 4]2×2 Matrix{Int64}: 1 2 3 4julia> rotl90(a,1)2×2 Matrix{Int64}: 2 4 1 3julia> rotl90(a,2)2×2 Matrix{Int64}: 4 3 2 1julia> rotl90(a,3)2×2 Matrix{Int64}: 3 1 4 2julia> rotl90(a,4)2×2 Matrix{Int64}: 1 2 3 4
Base.rotr90
—Functionrotr90(A)
Rotate matrixA
right 90 degrees.
Examples
julia> a = [1 2; 3 4]2×2 Matrix{Int64}: 1 2 3 4julia> rotr90(a)2×2 Matrix{Int64}: 3 1 4 2
rotr90(A, k)
Right-rotate matrixA
90 degrees clockwise an integerk
number of times. Ifk
is a multiple of four (including zero), this is equivalent to acopy
.
Examples
julia> a = [1 2; 3 4]2×2 Matrix{Int64}: 1 2 3 4julia> rotr90(a,1)2×2 Matrix{Int64}: 3 1 4 2julia> rotr90(a,2)2×2 Matrix{Int64}: 4 3 2 1julia> rotr90(a,3)2×2 Matrix{Int64}: 2 4 1 3julia> rotr90(a,4)2×2 Matrix{Int64}: 1 2 3 4
Base.mapslices
—Functionmapslices(f, A; dims)
Transform the given dimensions of arrayA
by applying a functionf
on each slice of the formA[..., :, ..., :, ...]
, with a colon at eachd
indims
. The results are concatenated along the remaining dimensions.
For example, ifdims = [1,2]
andA
is 4-dimensional, thenf
is called onx = A[:,:,i,j]
for alli
andj
, andf(x)
becomesR[:,:,i,j]
in the resultR
.
See alsoeachcol
oreachslice
, used withmap
orstack
.
Examples
julia> A = reshape(1:30,(2,5,3))2×5×3 reshape(::UnitRange{Int64}, 2, 5, 3) with eltype Int64:[:, :, 1] = 1 3 5 7 9 2 4 6 8 10[:, :, 2] = 11 13 15 17 19 12 14 16 18 20[:, :, 3] = 21 23 25 27 29 22 24 26 28 30julia> f(x::Matrix) = fill(x[1,1], 1,4); # returns a 1×4 matrixjulia> B = mapslices(f, A, dims=(1,2))1×4×3 Array{Int64, 3}:[:, :, 1] = 1 1 1 1[:, :, 2] = 11 11 11 11[:, :, 3] = 21 21 21 21julia> f2(x::AbstractMatrix) = fill(x[1,1], 1,4);julia> B == stack(f2, eachslice(A, dims=3))truejulia> g(x) = x[begin] // x[end-1]; # returns a numberjulia> mapslices(g, A, dims=[1,3])1×5×1 Array{Rational{Int64}, 3}:[:, :, 1] = 1//21 3//23 1//5 7//27 9//29julia> map(g, eachslice(A, dims=2))5-element Vector{Rational{Int64}}: 1//21 3//23 1//5 7//27 9//29julia> mapslices(sum, A; dims=(1,3)) == sum(A; dims=(1,3))true
Notice that ineachslice(A; dims=2)
, the specified dimension is the onewithout a colon in the slice. This isview(A,:,i,:)
, whereasmapslices(f, A; dims=(1,3))
usesA[:,i,:]
. The functionf
may mutate values in the slice without affectingA
.
Base.eachrow
—Functioneachrow(A::AbstractVecOrMat) <: AbstractVector
Create aRowSlices
object that is a vector of rows of matrix or vectorA
. Row slices are returned asAbstractVector
views ofA
.
For the inverse, seestack
(rows; dims=1)
.
See alsoeachcol
,eachslice
andmapslices
.
This function requires at least Julia 1.1.
Prior to Julia 1.9, this returned an iterator.
Examples
julia> a = [1 2; 3 4]2×2 Matrix{Int64}: 1 2 3 4julia> s = eachrow(a)2-element RowSlices{Matrix{Int64}, Tuple{Base.OneTo{Int64}}, SubArray{Int64, 1, Matrix{Int64}, Tuple{Int64, Base.Slice{Base.OneTo{Int64}}}, true}}: [1, 2] [3, 4]julia> s[1]2-element view(::Matrix{Int64}, 1, :) with eltype Int64: 1 2
Base.eachcol
—Functioneachcol(A::AbstractVecOrMat) <: AbstractVector
Create aColumnSlices
object that is a vector of columns of matrix or vectorA
. Column slices are returned asAbstractVector
views ofA
.
For the inverse, seestack
(cols)
orreduce(
hcat
, cols)
.
See alsoeachrow
,eachslice
andmapslices
.
This function requires at least Julia 1.1.
Prior to Julia 1.9, this returned an iterator.
Examples
julia> a = [1 2; 3 4]2×2 Matrix{Int64}: 1 2 3 4julia> s = eachcol(a)2-element ColumnSlices{Matrix{Int64}, Tuple{Base.OneTo{Int64}}, SubArray{Int64, 1, Matrix{Int64}, Tuple{Base.Slice{Base.OneTo{Int64}}, Int64}, true}}: [1, 3] [2, 4]julia> s[1]2-element view(::Matrix{Int64}, :, 1) with eltype Int64: 1 3
Base.eachslice
—Functioneachslice(A::AbstractArray; dims, drop=true)
Create aSlices
object that is an array of slices over dimensionsdims
ofA
, returning views that select all the data from the other dimensions inA
.dims
can either be an integer or a tuple of integers.
Ifdrop = true
(the default), the outerSlices
will drop the inner dimensions, and the ordering of the dimensions will match those indims
. Ifdrop = false
, then theSlices
will have the same dimensionality as the underlying array, with inner dimensions having size 1.
Seestack
(slices; dims)
for the inverse ofeachslice(A; dims::Integer)
.
See alsoeachrow
,eachcol
,mapslices
andselectdim
.
This function requires at least Julia 1.1.
Prior to Julia 1.9, this returned an iterator, and only a single dimensiondims
was supported.
Examples
julia> m = [1 2 3; 4 5 6; 7 8 9]3×3 Matrix{Int64}: 1 2 3 4 5 6 7 8 9julia> s = eachslice(m, dims=1)3-element RowSlices{Matrix{Int64}, Tuple{Base.OneTo{Int64}}, SubArray{Int64, 1, Matrix{Int64}, Tuple{Int64, Base.Slice{Base.OneTo{Int64}}}, true}}: [1, 2, 3] [4, 5, 6] [7, 8, 9]julia> s[1]3-element view(::Matrix{Int64}, 1, :) with eltype Int64: 1 2 3julia> eachslice(m, dims=1, drop=false)3×1 Slices{Matrix{Int64}, Tuple{Int64, Colon}, Tuple{Base.OneTo{Int64}, Base.OneTo{Int64}}, SubArray{Int64, 1, Matrix{Int64}, Tuple{Int64, Base.Slice{Base.OneTo{Int64}}}, true}, 2}: [1, 2, 3] [4, 5, 6] [7, 8, 9]
Base.invperm
—Functioninvperm(v)
Return the inverse permutation ofv
. IfB = A[v]
, thenA == B[invperm(v)]
.
See alsosortperm
,invpermute!
,isperm
,permutedims
.
Examples
julia> p = (2, 3, 1);julia> invperm(p)(3, 1, 2)julia> v = [2; 4; 3; 1];julia> invperm(v)4-element Vector{Int64}: 4 1 3 2julia> A = ['a','b','c','d'];julia> B = A[v]4-element Vector{Char}: 'b': ASCII/Unicode U+0062 (category Ll: Letter, lowercase) 'd': ASCII/Unicode U+0064 (category Ll: Letter, lowercase) 'c': ASCII/Unicode U+0063 (category Ll: Letter, lowercase) 'a': ASCII/Unicode U+0061 (category Ll: Letter, lowercase)julia> B[invperm(v)]4-element Vector{Char}: 'a': ASCII/Unicode U+0061 (category Ll: Letter, lowercase) 'b': ASCII/Unicode U+0062 (category Ll: Letter, lowercase) 'c': ASCII/Unicode U+0063 (category Ll: Letter, lowercase) 'd': ASCII/Unicode U+0064 (category Ll: Letter, lowercase)
Base.isperm
—Functionisperm(v) -> Bool
Returntrue
ifv
is a valid permutation.
Examples
julia> isperm([1; 2])truejulia> isperm([1; 3])false
Base.permute!
—Methodpermute!(v, p)
Permute vectorv
in-place, according to permutationp
. No checking is done to verify thatp
is a permutation.
To return a new permutation, usev[p]
. This is generally faster thanpermute!(v, p)
; it is even faster to write into a pre-allocated output array withu .= @view v[p]
. (Even thoughpermute!
overwritesv
in-place, it internally requires some allocation to keep track of which elements have been moved.)
Behavior can be unexpected when any mutated argument shares memory with any other argument.
See alsoinvpermute!
.
Examples
julia> A = [1, 1, 3, 4];julia> perm = [2, 4, 3, 1];julia> permute!(A, perm);julia> A4-element Vector{Int64}: 1 4 3 1
Base.invpermute!
—Functioninvpermute!(v, p)
Likepermute!
, but the inverse of the given permutation is applied.
Note that if you have a pre-allocated output array (e.g.u = similar(v)
), it is quicker to instead employu[p] = v
. (invpermute!
internally allocates a copy of the data.)
Behavior can be unexpected when any mutated argument shares memory with any other argument.
Examples
julia> A = [1, 1, 3, 4];julia> perm = [2, 4, 3, 1];julia> invpermute!(A, perm);julia> A4-element Vector{Int64}: 4 1 3 1
Base.reverse
—Methodreverse(A; dims=:)
ReverseA
along dimensiondims
, which can be an integer (a single dimension), a tuple of integers (a tuple of dimensions) or:
(reverse along all the dimensions, the default). See alsoreverse!
for in-place reversal.
Examples
julia> b = Int64[1 2; 3 4]2×2 Matrix{Int64}: 1 2 3 4julia> reverse(b, dims=2)2×2 Matrix{Int64}: 2 1 4 3julia> reverse(b)2×2 Matrix{Int64}: 4 3 2 1
Prior to Julia 1.6, only single-integerdims
are supported inreverse
.
Base.reverseind
—Functionreverseind(v, i)
Given an indexi
inreverse(v)
, return the corresponding index inv
so thatv[reverseind(v,i)] == reverse(v)[i]
. (This can be nontrivial in cases wherev
contains non-ASCII characters.)
Examples
julia> s = "Julia🚀""Julia🚀"julia> r = reverse(s)"🚀ailuJ"julia> for i in eachindex(s) print(r[reverseind(r, i)]) endJulia🚀
Base.reverse!
—Functionreverse!(v [, start=firstindex(v) [, stop=lastindex(v) ]]) -> v
In-place version ofreverse
.
Examples
julia> A = Vector(1:5)5-element Vector{Int64}: 1 2 3 4 5julia> reverse!(A);julia> A5-element Vector{Int64}: 5 4 3 2 1
reverse!(A; dims=:)
Likereverse
, but operates in-place inA
.
Multidimensionalreverse!
requires Julia 1.6.
Settings
This document was generated withDocumenter.jl version 1.8.0 onWednesday 9 July 2025. Using Julia version 1.11.6.