Arrays
Constructors and Types
Core.AbstractArray
— Type.AbstractArray{T, N}
Abstract array supertype which arrays inherit from.
Core.Array
— Type.Array{T}(dims)
Array{T,N}(dims)
Construct an uninitialized N
-dimensional dense array with element type T
, where N
is determined from the length or number of dims
. dims
may be a tuple or a series of integer arguments corresponding to the lengths in each dimension. If the rank N
is supplied explicitly as in Array{T,N}(dims)
, then it must match the length or number of dims
.
Example
julia> A = Array{Float64, 2}(2, 2);
julia> ndims(A)
2
julia> eltype(A)
Float64
Base.getindex
— Method.getindex(type[, elements...])
Construct a 1-d array of the specified type. This is usually called with the syntax Type[]
. Element values can be specified using Type[a,b,c,...]
.
julia> Int8[1, 2, 3]
3-element Array{Int8,1}:
1
2
3
julia> getindex(Int8, 1, 2, 3)
3-element Array{Int8,1}:
1
2
3
Base.zeros
— Function.zeros([A::AbstractArray,] [T=eltype(A)::Type,] [dims=size(A)::Tuple])
Create an array of all zeros with the same layout as A
, element type T
and size dims
. The A
argument can be skipped, which behaves like Array{Float64,0}()
was passed. For convenience dims
may also be passed in variadic form.
julia> zeros(1)
1-element Array{Float64,1}:
0.0
julia> zeros(Int8, 2, 3)
2×3 Array{Int8,2}:
0 0 0
0 0 0
julia> A = [1 2; 3 4]
2×2 Array{Int64,2}:
1 2
3 4
julia> zeros(A)
2×2 Array{Int64,2}:
0 0
0 0
julia> zeros(A, Float64)
2×2 Array{Float64,2}:
0.0 0.0
0.0 0.0
julia> zeros(A, Bool, (3,))
3-element Array{Bool,1}:
false
false
false
Base.ones
— Function.ones([A::AbstractArray,] [T=eltype(A)::Type,] [dims=size(A)::Tuple])
Create an array of all ones with the same layout as A
, element type T
and size dims
. The A
argument can be skipped, which behaves like Array{Float64,0}()
was passed. For convenience dims
may also be passed in variadic form.
julia> ones(Complex128, 2, 3)
2×3 Array{Complex{Float64},2}:
1.0+0.0im 1.0+0.0im 1.0+0.0im
1.0+0.0im 1.0+0.0im 1.0+0.0im
julia> ones(1,2)
1×2 Array{Float64,2}:
1.0 1.0
julia> A = [1 2; 3 4]
2×2 Array{Int64,2}:
1 2
3 4
julia> ones(A)
2×2 Array{Int64,2}:
1 1
1 1
julia> ones(A, Float64)
2×2 Array{Float64,2}:
1.0 1.0
1.0 1.0
julia> ones(A, Bool, (3,))
3-element Array{Bool,1}:
true
true
true
Base.BitArray
— Type.BitArray(dims::Integer...)
BitArray{N}(dims::NTuple{N,Int})
Construct an uninitialized BitArray
with the given dimensions. Behaves identically to the Array
constructor.
julia> BitArray(2, 2)
2×2 BitArray{2}:
false false
false true
julia> BitArray((3, 1))
3×1 BitArray{2}:
false
true
false
BitArray(itr)
Construct a BitArray
generated by the given iterable object. The shape is inferred from the itr
object.
julia> BitArray([1 0; 0 1])
2×2 BitArray{2}:
true false
false true
julia> BitArray(x+y == 3 for x = 1:2, y = 1:3)
2×3 BitArray{2}:
false true false
true false false
julia> BitArray(x+y == 3 for x = 1:2 for y = 1:3)
6-element BitArray{1}:
false
true
false
true
false
false
Base.trues
— Function.trues(dims)
Create a BitArray
with all values set to true
.
julia> trues(2,3)
2×3 BitArray{2}:
true true true
true true true
trues(A)
Create a BitArray
with all values set to true
of the same shape as A
.
julia> A = [1 2; 3 4]
2×2 Array{Int64,2}:
1 2
3 4
julia> trues(A)
2×2 BitArray{2}:
true true
true true
Base.falses
— Function.falses(dims)
Create a BitArray
with all values set to false
.
julia> falses(2,3)
2×3 BitArray{2}:
false false false
false false false
falses(A)
Create a BitArray
with all values set to false
of the same shape as A
.
julia> A = [1 2; 3 4]
2×2 Array{Int64,2}:
1 2
3 4
julia> falses(A)
2×2 BitArray{2}:
false false
false false
Base.fill
— Function.fill(x, dims)
Create an array filled with the value x
. For example, fill(1.0, (5,5))
returns a 5×5 array of floats, with each element initialized to 1.0
.
julia> fill(1.0, (5,5))
5×5 Array{Float64,2}:
1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0 1.0
If x
is an object reference, all elements will refer to the same object. fill(Foo(), dims)
will return an array filled with the result of evaluating Foo()
once.
Base.fill!
— Function.fill!(A, x)
Fill array A
with the value x
. If x
is an object reference, all elements will refer to the same object. fill!(A, Foo())
will return A
filled with the result of evaluating Foo()
once.
julia> A = zeros(2,3)
2×3 Array{Float64,2}:
0.0 0.0 0.0
0.0 0.0 0.0
julia> fill!(A, 2.)
2×3 Array{Float64,2}:
2.0 2.0 2.0
2.0 2.0 2.0
julia> a = [1, 1, 1]; A = fill!(Vector{Vector{Int}}(3), a); a[1] = 2; A
3-element Array{Array{Int64,1},1}:
[2, 1, 1]
[2, 1, 1]
[2, 1, 1]
julia> x = 0; f() = (global x += 1; x); fill!(Vector{Int}(3), f())
3-element Array{Int64,1}:
1
1
1
Base.similar
— Method.similar(array, [element_type=eltype(array)], [dims=size(array)])
Create an uninitialized mutable array with the given element type and size, based upon the given source array. The second and third arguments are both optional, defaulting to the given array's eltype
and size
. The dimensions may be specified either as a single tuple argument or as a series of integer arguments.
Custom AbstractArray subtypes may choose which specific array type is best-suited to return for the given element type and dimensionality. If they do not specialize this method, the default is an Array{element_type}(dims...)
.
For example, similar(1:10, 1, 4)
returns an uninitialized Array{Int,2}
since ranges are neither mutable nor support 2 dimensions:
julia> similar(1:10, 1, 4)
1×4 Array{Int64,2}:
4419743872 4374413872 4419743888 0
Conversely, similar(trues(10,10), 2)
returns an uninitialized BitVector
with two elements since BitArray
s are both mutable and can support 1-dimensional arrays:
julia> similar(trues(10,10), 2)
2-element BitArray{1}:
false
false
Since BitArray
s can only store elements of type Bool
, however, if you request a different element type it will create a regular Array
instead:
julia> similar(falses(10), Float64, 2, 4)
2×4 Array{Float64,2}:
2.18425e-314 2.18425e-314 2.18425e-314 2.18425e-314
2.18425e-314 2.18425e-314 2.18425e-314 2.18425e-314
Base.similar
— Method.similar(storagetype, indices)
Create an uninitialized mutable array analogous to that specified by storagetype
, but with indices
specified by the last argument. storagetype
might be a type or a function.
Examples:
similar(Array{Int}, indices(A))
creates an array that "acts like" an Array{Int}
(and might indeed be backed by one), but which is indexed identically to A
. If A
has conventional indexing, this will be identical to Array{Int}(size(A))
, but if A
has unconventional indexing then the indices of the result will match A
.
similar(BitArray, (indices(A, 2),))
would create a 1-dimensional logical array whose indices match those of the columns of A
.
similar(dims->zeros(Int, dims), indices(A))
would create an array of Int
, initialized to zero, matching the indices of A
.
Base.eye
— Function.eye([T::Type=Float64,] m::Integer, n::Integer)
m
-by-n
identity matrix. The default element type is Float64
.
eye(m, n)
m
-by-n
identity matrix.
eye([T::Type=Float64,] n::Integer)
n
-by-n
identity matrix. The default element type is Float64
.
eye(A)
Constructs an identity matrix of the same dimensions and type as A
.
julia> A = [1 2 3; 4 5 6; 7 8 9]
3×3 Array{Int64,2}:
1 2 3
4 5 6
7 8 9
julia> eye(A)
3×3 Array{Int64,2}:
1 0 0
0 1 0
0 0 1
Note the difference from ones
.
Base.linspace
— Function.linspace(start, stop, n=50)
Construct a range of n
linearly spaced elements from start
to stop
.
julia> linspace(1.3,2.9,9)
1.3:0.2:2.9
Base.logspace
— Function.logspace(start::Real, stop::Real, n::Integer=50)
Construct a vector of n
logarithmically spaced numbers from 10^start
to 10^stop
.
julia> logspace(1.,10.,5)
5-element Array{Float64,1}:
10.0
1778.28
3.16228e5
5.62341e7
1.0e10
Base.Random.randsubseq
— Function.randsubseq(A, p) -> Vector
Return a vector consisting of a random subsequence of the given array A
, where each element of A
is included (in order) with independent probability p
. (Complexity is linear in p*length(A)
, so this function is efficient even if p
is small and A
is large.) Technically, this process is known as "Bernoulli sampling" of A
.
Base.Random.randsubseq!
— Function.randsubseq!(S, A, p)
Like randsubseq
, but the results are stored in S
(which is resized as needed).
Basic functions
Base.ndims
— Function.ndims(A::AbstractArray) -> Integer
Returns the number of dimensions of A
.
julia> A = ones(3,4,5);
julia> ndims(A)
3
Base.size
— Function.size(A::AbstractArray, [dim...])
Returns a tuple containing the dimensions of A
. Optionally you can specify the dimension(s) you want the length of, and get the length of that dimension, or a tuple of the lengths of dimensions you asked for.
julia> A = ones(2,3,4);
julia> size(A, 2)
3
julia> size(A,3,2)
(4, 3)
Base.indices
— Method.indices(A)
Returns the tuple of valid indices for array A
.
julia> A = ones(5,6,7);
julia> indices(A)
(Base.OneTo(5), Base.OneTo(6), Base.OneTo(7))
Base.indices
— Method.indices(A, d)
Returns the valid range of indices for array A
along dimension d
.
julia> A = ones(5,6,7);
julia> indices(A,2)
Base.OneTo(6)
Base.length
— Method.length(A::AbstractArray) -> Integer
Returns the number of elements in A
.
julia> A = ones(3,4,5);
julia> length(A)
60
Base.eachindex
— Function.eachindex(A...)
Creates an iterable object for visiting each index of an AbstractArray A
in an efficient manner. For array types that have opted into fast linear indexing (like Array
), this is simply the range 1:length(A)
. For other array types, this returns a specialized Cartesian range to efficiently index into the array with indices specified for every dimension. For other iterables, including strings and dictionaries, this returns an iterator object supporting arbitrary index types (e.g. unevenly spaced or non-integer indices).
Example for a sparse 2-d array:
julia> A = sparse([1, 1, 2], [1, 3, 1], [1, 2, -5])
2×3 SparseMatrixCSC{Int64,Int64} with 3 stored entries:
[1, 1] = 1
[2, 1] = -5
[1, 3] = 2
julia> for iter in eachindex(A)
@show iter.I[1], iter.I[2]
@show A[iter]
end
(iter.I[1], iter.I[2]) = (1, 1)
A[iter] = 1
(iter.I[1], iter.I[2]) = (2, 1)
A[iter] = -5
(iter.I[1], iter.I[2]) = (1, 2)
A[iter] = 0
(iter.I[1], iter.I[2]) = (2, 2)
A[iter] = 0
(iter.I[1], iter.I[2]) = (1, 3)
A[iter] = 2
(iter.I[1], iter.I[2]) = (2, 3)
A[iter] = 0
If you supply more than one AbstractArray
argument, eachindex
will create an iterable object that is fast for all arguments (a UnitRange
if all inputs have fast linear indexing, a CartesianRange
otherwise). If the arrays have different sizes and/or dimensionalities, eachindex
returns an iterable that spans the largest range along each dimension.
Base.linearindices
— Function.linearindices(A)
Returns a UnitRange
specifying the valid range of indices for A[i]
where i
is an Int
. For arrays with conventional indexing (indices start at 1), or any multidimensional array, this is 1:length(A)
; however, for one-dimensional arrays with unconventional indices, this is indices(A, 1)
.
Calling this function is the "safe" way to write algorithms that exploit linear indexing.
julia> A = ones(5,6,7);
julia> b = linearindices(A);
julia> extrema(b)
(1, 210)
Base.IndexStyle
— Type.IndexStyle(A)
IndexStyle(typeof(A))
IndexStyle
specifies the "native indexing style" for array A
. When you define a new AbstractArray
type, you can choose to implement either linear indexing or cartesian indexing. If you decide to implement linear indexing, then you must set this trait for your array type:
Base.IndexStyle(::Type{<:MyArray}) = IndexLinear()
The default is IndexCartesian()
.
Julia's internal indexing machinery will automatically (and invisibly) convert all indexing operations into the preferred style using sub2ind
or ind2sub
. This allows users to access elements of your array using any indexing style, even when explicit methods have not been provided.
If you define both styles of indexing for your AbstractArray
, this trait can be used to select the most performant indexing style. Some methods check this trait on their inputs, and dispatch to different algorithms depending on the most efficient access pattern. In particular, eachindex
creates an iterator whose type depends on the setting of this trait.
Base.countnz
— Function.countnz(A) -> Integer
Counts the number of nonzero values in array A
(dense or sparse). Note that this is not a constant-time operation. For sparse matrices, one should usually use nnz
, which returns the number of stored values.
julia> A = [1 2 4; 0 0 1; 1 1 0]
3×3 Array{Int64,2}:
1 2 4
0 0 1
1 1 0
julia> countnz(A)
6
Base.conj!
— Function.conj!(A)
Transform an array to its complex conjugate in-place.
See also conj
.
julia> A = [1+im 2-im; 2+2im 3+im]
2×2 Array{Complex{Int64},2}:
1+1im 2-1im
2+2im 3+1im
julia> conj!(A);
julia> A
2×2 Array{Complex{Int64},2}:
1-1im 2+1im
2-2im 3-1im
Base.stride
— Function.stride(A, k::Integer)
Returns the distance in memory (in number of elements) between adjacent elements in dimension k
.
julia> A = ones(3,4,5);
julia> stride(A,2)
3
julia> stride(A,3)
12
Base.strides
— Function.strides(A)
Returns a tuple of the memory strides in each dimension.
julia> A = ones(3,4,5);
julia> strides(A)
(1, 3, 12)
Base.ind2sub
— Function.ind2sub(a, index) -> subscripts
Returns a tuple of subscripts into array a
corresponding to the linear index index
.
julia> A = ones(5,6,7);
julia> ind2sub(A,35)
(5, 1, 2)
julia> ind2sub(A,70)
(5, 2, 3)
ind2sub(dims, index) -> subscripts
Returns a tuple of subscripts into an array with dimensions dims
, corresponding to the linear index index
.
Example:
i, j, ... = ind2sub(size(A), indmax(A))
provides the indices of the maximum element.
julia> ind2sub((3,4),2)
(2, 1)
julia> ind2sub((3,4),3)
(3, 1)
julia> ind2sub((3,4),4)
(1, 2)
Base.sub2ind
— Function.sub2ind(dims, i, j, k...) -> index
The inverse of ind2sub
, returns the linear index corresponding to the provided subscripts.
julia> sub2ind((5,6,7),1,2,3)
66
julia> sub2ind((5,6,7),1,6,3)
86
Base.LinAlg.checksquare
— Function.LinAlg.checksquare(A)
Check that a matrix is square, then return its common dimension. For multiple arguments, return a vector.
Example
julia> A = ones(4,4); B = zeros(5,5);
julia> LinAlg.checksquare(A, B)
2-element Array{Int64,1}:
4
5
Broadcast and vectorization
See also the dot syntax for vectorizing functions; for example, f.(args...)
implicitly calls broadcast(f, args...)
. Rather than relying on "vectorized" methods of functions like sin
to operate on arrays, you should use sin.(a)
to vectorize via broadcast
.
Base.broadcast
— Function.broadcast(f, As...)
Broadcasts the arrays, tuples, Ref
s, nullables, and/or scalars As
to a container of the appropriate type and dimensions. In this context, anything that is not a subtype of AbstractArray
, Ref
(except for Ptr
s), Tuple
, or Nullable
is considered a scalar. The resulting container is established by the following rules:
If all the arguments are scalars, it returns a scalar.
If the arguments are tuples and zero or more scalars, it returns a tuple.
If the arguments contain at least one array or
Ref
, it returns an array (expanding singleton dimensions), and treatsRef
s as 0-dimensional arrays, and tuples as 1-dimensional arrays.
The following additional rule applies to Nullable
arguments: If there is at least one Nullable
, and all the arguments are scalars or Nullable
, it returns a Nullable
treating Nullable
s as "containers".
A special syntax exists for broadcasting: f.(args...)
is equivalent to broadcast(f, args...)
, and nested f.(g.(args...))
calls are fused into a single broadcast loop.
julia> A = [1, 2, 3, 4, 5]
5-element Array{Int64,1}:
1
2
3
4
5
julia> B = [1 2; 3 4; 5 6; 7 8; 9 10]
5×2 Array{Int64,2}:
1 2
3 4
5 6
7 8
9 10
julia> broadcast(+, A, B)
5×2 Array{Int64,2}:
2 3
5 6
8 9
11 12
14 15
julia> parse.(Int, ["1", "2"])
2-element Array{Int64,1}:
1
2
julia> abs.((1, -2))
(1, 2)
julia> broadcast(+, 1.0, (0, -2.0))
(1.0, -1.0)
julia> broadcast(+, 1.0, (0, -2.0), Ref(1))
2-element Array{Float64,1}:
2.0
0.0
julia> (+).([[0,2], [1,3]], Ref{Vector{Int}}([1,-1]))
2-element Array{Array{Int64,1},1}:
[1, 1]
[2, 2]
julia> string.(("one","two","three","four"), ": ", 1:4)
4-element Array{String,1}:
"one: 1"
"two: 2"
"three: 3"
"four: 4"
julia> Nullable("X") .* "Y"
Nullable{String}("XY")
julia> broadcast(/, 1.0, Nullable(2.0))
Nullable{Float64}(0.5)
julia> (1 + im) ./ Nullable{Int}()
Nullable{Complex{Float64}}()
Base.broadcast!
— Function.broadcast!(f, dest, As...)
Like broadcast
, but store the result of broadcast(f, As...)
in the dest
array. Note that dest
is only used to store the result, and does not supply arguments to f
unless it is also listed in the As
, as in broadcast!(f, A, A, B)
to perform A[:] = broadcast(f, A, B)
.
Base.Broadcast.@__dot__
— Macro.@. expr
Convert every function call or operator in expr
into a "dot call" (e.g. convert f(x)
to f.(x)
), and convert every assignment in expr
to a "dot assignment" (e.g. convert +=
to .+=
).
If you want to avoid adding dots for selected function calls in expr
, splice those function calls in with $
. For example, @. sqrt(abs($sort(x)))
is equivalent to sqrt.(abs.(sort(x)))
(no dot for sort
).
(@.
is equivalent to a call to @__dot__
.)
Base.Broadcast.broadcast_getindex
— Function.broadcast_getindex(A, inds...)
Broadcasts the inds
arrays to a common size like broadcast
and returns an array of the results A[ks...]
, where ks
goes over the positions in the broadcast result A
.
julia> A = [1, 2, 3, 4, 5]
5-element Array{Int64,1}:
1
2
3
4
5
julia> B = [1 2; 3 4; 5 6; 7 8; 9 10]
5×2 Array{Int64,2}:
1 2
3 4
5 6
7 8
9 10
julia> C = broadcast(+,A,B)
5×2 Array{Int64,2}:
2 3
5 6
8 9
11 12
14 15
julia> broadcast_getindex(C,[1,2,10])
3-element Array{Int64,1}:
2
5
15
Base.Broadcast.broadcast_setindex!
— Function.broadcast_setindex!(A, X, inds...)
Broadcasts the X
and inds
arrays to a common size and stores the value from each position in X
at the indices in A
given by the same positions in inds
.
Indexing and assignment
Base.getindex
— Method.getindex(A, inds...)
Returns a subset of array A
as specified by inds
, where each ind
may be an Int
, a Range
, or a Vector
. See the manual section on array indexing for details.
julia> A = [1 2; 3 4]
2×2 Array{Int64,2}:
1 2
3 4
julia> getindex(A, 1)
1
julia> getindex(A, [2, 1])
2-element Array{Int64,1}:
3
1
julia> getindex(A, 2:4)
3-element Array{Int64,1}:
3
2
4
Base.setindex!
— Method.setindex!(A, X, inds...)
Store values from array X
within some subset of A
as specified by inds
.
Base.copy!
— Method.copy!(dest, Rdest::CartesianRange, src, Rsrc::CartesianRange) -> dest
Copy the block of src
in the range of Rsrc
to the block of dest
in the range of Rdest
. The sizes of the two regions must match.
Base.isassigned
— Function.isassigned(array, i) -> Bool
Tests whether the given array has a value associated with index i
. Returns false
if the index is out of bounds, or has an undefined reference.
julia> isassigned(rand(3, 3), 5)
true
julia> isassigned(rand(3, 3), 3 * 3 + 1)
false
julia> mutable struct Foo end
julia> v = similar(rand(3), Foo)
3-element Array{Foo,1}:
#undef
#undef
#undef
julia> isassigned(v, 1)
false
Base.Colon
— Type.Colon()
Colons (:) are used to signify indexing entire objects or dimensions at once.
Very few operations are defined on Colons directly; instead they are converted by to_indices
to an internal vector type (Base.Slice
) to represent the collection of indices they span before being used.
Base.IteratorsMD.CartesianIndex
— Type.CartesianIndex(i, j, k...) -> I
CartesianIndex((i, j, k...)) -> I
Create a multidimensional index I
, which can be used for indexing a multidimensional array A
. In particular, A[I]
is equivalent to A[i,j,k...]
. One can freely mix integer and CartesianIndex
indices; for example, A[Ipre, i, Ipost]
(where Ipre
and Ipost
are CartesianIndex
indices and i
is an Int
) can be a useful expression when writing algorithms that work along a single dimension of an array of arbitrary dimensionality.
A CartesianIndex
is sometimes produced by eachindex
, and always when iterating with an explicit CartesianRange
.
Base.IteratorsMD.CartesianRange
— Type.CartesianRange(Istart::CartesianIndex, Istop::CartesianIndex) -> R
CartesianRange(sz::Dims) -> R
CartesianRange(istart:istop, jstart:jstop, ...) -> R
Define a region R
spanning a multidimensional rectangular range of integer indices. These are most commonly encountered in the context of iteration, where for I in R ... end
will return CartesianIndex
indices I
equivalent to the nested loops
for j = jstart:jstop
for i = istart:istop
...
end
end
Consequently these can be useful for writing algorithms that work in arbitrary dimensions.
Base.to_indices
— Function.to_indices(A, I::Tuple)
Convert the tuple I
to a tuple of indices for use in indexing into array A
.
The returned tuple must only contain either Int
s or AbstractArray
s of scalar indices that are supported by array A
. It will error upon encountering a novel index type that it does not know how to process.
For simple index types, it defers to the unexported Base.to_index(A, i)
to process each index i
. While this internal function is not intended to be called directly, Base.to_index
may be extended by custom array or index types to provide custom indexing behaviors.
More complicated index types may require more context about the dimension into which they index. To support those cases, to_indices(A, I)
calls to_indices(A, indices(A), I)
, which then recursively walks through both the given tuple of indices and the dimensional indices of A
in tandem. As such, not all index types are guaranteed to propagate to Base.to_index
.
Base.checkbounds
— Function.checkbounds(Bool, A, I...)
Return true
if the specified indices I
are in bounds for the given array A
. Subtypes of AbstractArray
should specialize this method if they need to provide custom bounds checking behaviors; however, in many cases one can rely on A
's indices and checkindex
.
See also checkindex
.
julia> A = rand(3, 3);
julia> checkbounds(Bool, A, 2)
true
julia> checkbounds(Bool, A, 3, 4)
false
julia> checkbounds(Bool, A, 1:3)
true
julia> checkbounds(Bool, A, 1:3, 2:4)
false
checkbounds(A, I...)
Throw an error if the specified indices I
are not in bounds for the given array A
.
Base.checkindex
— Function.checkindex(Bool, inds::AbstractUnitRange, index)
Return true
if the given index
is within the bounds of inds
. Custom types that would like to behave as indices for all arrays can extend this method in order to provide a specialized bounds checking implementation.
julia> checkindex(Bool,1:20,8)
true
julia> checkindex(Bool,1:20,21)
false
Views (SubArrays and other view types)
Base.view
— Function.view(A, inds...)
Like getindex
, but returns a view into the parent array A
with the given indices instead of making a copy. Calling getindex
or setindex!
on the returned SubArray
computes the indices to the parent array on the fly without checking bounds.
julia> A = [1 2; 3 4]
2×2 Array{Int64,2}:
1 2
3 4
julia> b = view(A, :, 1)
2-element SubArray{Int64,1,Array{Int64,2},Tuple{Base.Slice{Base.OneTo{Int64}},Int64},true}:
1
3
julia> fill!(b, 0)
2-element SubArray{Int64,1,Array{Int64,2},Tuple{Base.Slice{Base.OneTo{Int64}},Int64},true}:
0
0
julia> A # Note A has changed even though we modified b
2×2 Array{Int64,2}:
0 2
0 4
Base.@view
— Macro.@view A[inds...]
Creates a SubArray
from an indexing expression. This can only be applied directly to a reference expression (e.g. @view A[1,2:end]
), and should not be used as the target of an assignment (e.g. @view(A[1,2:end]) = ...
). See also @views
to switch an entire block of code to use views for slicing.
julia> A = [1 2; 3 4]
2×2 Array{Int64,2}:
1 2
3 4
julia> b = @view A[:, 1]
2-element SubArray{Int64,1,Array{Int64,2},Tuple{Base.Slice{Base.OneTo{Int64}},Int64},true}:
1
3
julia> fill!(b, 0)
2-element SubArray{Int64,1,Array{Int64,2},Tuple{Base.Slice{Base.OneTo{Int64}},Int64},true}:
0
0
julia> A
2×2 Array{Int64,2}:
0 2
0 4
Base.@views
— Macro.@views expression
Convert every array-slicing operation in the given expression (which may be a begin
/end
block, loop, function, etc.) to return a view. Scalar indices, non-array types, and explicit getindex
calls (as opposed to array[...]
) are unaffected.
Note that the @views
macro only affects array[...]
expressions that appear explicitly in the given expression
, not array slicing that occurs in functions called by that code.
Base.parent
— Function.parent(A)
Returns the "parent array" of an array view type (e.g., SubArray
), or the array itself if it is not a view.
Base.parentindexes
— Function.parentindexes(A)
From an array view A
, returns the corresponding indexes in the parent.
Base.slicedim
— Function.slicedim(A, d::Integer, i)
Return all the data of A
where the index for dimension d
equals i
. Equivalent to A[:,:,...,i,:,:,...]
where i
is in position d
.
julia> A = [1 2 3 4; 5 6 7 8]
2×4 Array{Int64,2}:
1 2 3 4
5 6 7 8
julia> slicedim(A,2,3)
2-element Array{Int64,1}:
3
7
Base.reinterpret
— Function.reinterpret(type, A)
Change the type-interpretation of a block of memory. For arrays, this constructs an array with the same binary data as the given array, but with the specified element type. For example, reinterpret(Float32, UInt32(7))
interprets the 4 bytes corresponding to UInt32(7)
as a Float32
.
julia> reinterpret(Float32, UInt32(7))
1.0f-44
julia> reinterpret(Float32, UInt32[1 2 3 4 5])
1×5 Array{Float32,2}:
1.4013f-45 2.8026f-45 4.2039f-45 5.60519f-45 7.00649f-45
Base.reshape
— Function.reshape(A, dims...) -> R
reshape(A, dims) -> R
Return an array R
with the same data as A
, but with different dimension sizes or number of dimensions. The two arrays share the same underlying data, so that setting elements of R
alters the values of A
and vice versa.
The new dimensions may be specified either as a list of arguments or as a shape tuple. At most one dimension may be specified with a :
, in which case its length is computed such that its product with all the specified dimensions is equal to the length of the original array A
. The total number of elements must not change.
julia> A = collect(1:16)
16-element Array{Int64,1}:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
julia> reshape(A, (4, 4))
4×4 Array{Int64,2}:
1 5 9 13
2 6 10 14
3 7 11 15
4 8 12 16
julia> reshape(A, 2, :)
2×8 Array{Int64,2}:
1 3 5 7 9 11 13 15
2 4 6 8 10 12 14 16
Base.squeeze
— Function.squeeze(A, dims)
Remove the dimensions specified by dims
from array A
. Elements of dims
must be unique and within the range 1:ndims(A)
. size(A,i)
must equal 1 for all i
in dims
.
julia> a = reshape(collect(1:4),(2,2,1,1))
2×2×1×1 Array{Int64,4}:
[:, :, 1, 1] =
1 3
2 4
julia> squeeze(a,3)
2×2×1 Array{Int64,3}:
[:, :, 1] =
1 3
2 4
Base.vec
— Function.vec(a::AbstractArray) -> Vector
Reshape the array a
as a one-dimensional column vector. The resulting array shares the same underlying data as a
, so modifying one will also modify the other.
julia> a = [1 2 3; 4 5 6]
2×3 Array{Int64,2}:
1 2 3
4 5 6
julia> vec(a)
6-element Array{Int64,1}:
1
4
2
5
3
6
See also reshape
.
Concatenation and permutation
Base.cat
— Function.cat(dims, A...)
Concatenate the input arrays along the specified dimensions in the iterable dims
. For dimensions not in dims
, all input arrays should have the same size, which will also be the size of the output array along that dimension. For dimensions in dims
, the size of the output array is the sum of the sizes of the input arrays along that dimension. If dims
is a single number, the different arrays are tightly stacked along that dimension. If dims
is an iterable containing several dimensions, this allows one to construct block diagonal matrices and their higher-dimensional analogues by simultaneously increasing several dimensions for every new input array and putting zero blocks elsewhere. For example, cat([1,2], matrices...)
builds a block diagonal matrix, i.e. a block matrix with matrices[1]
, matrices[2]
, ... as diagonal blocks and matching zero blocks away from the diagonal.
Base.vcat
— Function.vcat(A...)
Concatenate along dimension 1.
julia> a = [1 2 3 4 5]
1×5 Array{Int64,2}:
1 2 3 4 5
julia> b = [6 7 8 9 10; 11 12 13 14 15]
2×5 Array{Int64,2}:
6 7 8 9 10
11 12 13 14 15
julia> vcat(a,b)
3×5 Array{Int64,2}:
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
julia> c = ([1 2 3], [4 5 6])
([1 2 3], [4 5 6])
julia> vcat(c...)
2×3 Array{Int64,2}:
1 2 3
4 5 6
Base.hcat
— Function.hcat(A...)
Concatenate along dimension 2.
julia> a = [1; 2; 3; 4; 5]
5-element Array{Int64,1}:
1
2
3
4
5
julia> b = [6 7; 8 9; 10 11; 12 13; 14 15]
5×2 Array{Int64,2}:
6 7
8 9
10 11
12 13
14 15
julia> hcat(a,b)
5×3 Array{Int64,2}:
1 6 7
2 8 9
3 10 11
4 12 13
5 14 15
julia> c = ([1; 2; 3], [4; 5; 6])
([1, 2, 3], [4, 5, 6])
julia> hcat(c...)
3×2 Array{Int64,2}:
1 4
2 5
3 6
Base.hvcat
— Function.hvcat(rows::Tuple{Vararg{Int}}, values...)
Horizontal and vertical concatenation in one call. This function is called for block matrix syntax. The first argument specifies the number of arguments to concatenate in each block row.
julia> a, b, c, d, e, f = 1, 2, 3, 4, 5, 6
(1, 2, 3, 4, 5, 6)
julia> [a b c; d e f]
2×3 Array{Int64,2}:
1 2 3
4 5 6
julia> hvcat((3,3), a,b,c,d,e,f)
2×3 Array{Int64,2}:
1 2 3
4 5 6
julia> [a b;c d; e f]
3×2 Array{Int64,2}:
1 2
3 4
5 6
julia> hvcat((2,2,2), a,b,c,d,e,f)
3×2 Array{Int64,2}:
1 2
3 4
5 6
If the first argument is a single integer n
, then all block rows are assumed to have n
block columns.
Base.flipdim
— Function.flipdim(A, d::Integer)
Reverse A
in dimension d
.
julia> b = [1 2; 3 4]
2×2 Array{Int64,2}:
1 2
3 4
julia> flipdim(b,2)
2×2 Array{Int64,2}:
2 1
4 3
Base.circshift
— Function.circshift(A, shifts)
Circularly shift the data in an array. The second argument is a vector giving the amount to shift in each dimension.
julia> b = reshape(collect(1:16), (4,4))
4×4 Array{Int64,2}:
1 5 9 13
2 6 10 14
3 7 11 15
4 8 12 16
julia> circshift(b, (0,2))
4×4 Array{Int64,2}:
9 13 1 5
10 14 2 6
11 15 3 7
12 16 4 8
julia> circshift(b, (-1,0))
4×4 Array{Int64,2}:
2 6 10 14
3 7 11 15
4 8 12 16
1 5 9 13
See also circshift!
.
Base.circshift!
— Function.circshift!(dest, src, shifts)
Circularly shift the data in src
, storing the result in dest
. shifts
specifies the amount to shift in each dimension.
The dest
array must be distinct from the src
array (they cannot alias each other).
See also circshift
.
Base.circcopy!
— Function.circcopy!(dest, src)
Copy src
to dest
, indexing each dimension modulo its length. src
and dest
must have the same size, but can be offset in their indices; any offset results in a (circular) wraparound. If the arrays have overlapping indices, then on the domain of the overlap dest
agrees with src
.
julia> src = reshape(collect(1:16), (4,4))
4×4 Array{Int64,2}:
1 5 9 13
2 6 10 14
3 7 11 15
4 8 12 16
julia> dest = OffsetArray{Int}((0:3,2:5))
julia> circcopy!(dest, src)
OffsetArrays.OffsetArray{Int64,2,Array{Int64,2}} with indices 0:3×2:5:
8 12 16 4
5 9 13 1
6 10 14 2
7 11 15 3
julia> dest[1:3,2:4] == src[1:3,2:4]
true
Base.contains
— Method.contains(fun, itr, x) -> Bool
Returns true
if there is at least one element y
in itr
such that fun(y,x)
is true
.
julia> vec = [10, 100, 200]
3-element Array{Int64,1}:
10
100
200
julia> contains(==, vec, 200)
true
julia> contains(==, vec, 300)
false
julia> contains(>, vec, 100)
true
julia> contains(>, vec, 200)
false
Base.find
— Method.find(A)
Return a vector of the linear indexes of the non-zeros in A
(determined by A[i]!=0
). A common use of this is to convert a boolean array to an array of indexes of the true
elements. If there are no non-zero elements of A
, find
returns an empty array.
julia> A = [true false; false true]
2×2 Array{Bool,2}:
true false
false true
julia> find(A)
2-element Array{Int64,1}:
1
4
Base.find
— Method.find(f::Function, A)
Return a vector I
of the linear indexes of A
where f(A[I])
returns true
. If there are no such elements of A
, find returns an empty array.
julia> A = [1 2; 3 4]
2×2 Array{Int64,2}:
1 2
3 4
julia> find(isodd,A)
2-element Array{Int64,1}:
1
2
Base.findn
— Function.findn(A)
Return a vector of indexes for each dimension giving the locations of the non-zeros in A
(determined by A[i]!=0
). If there are no non-zero elements of A
, findn
returns a 2-tuple of empty arrays.
julia> A = [1 2 0; 0 0 3; 0 4 0]
3×3 Array{Int64,2}:
1 2 0
0 0 3
0 4 0
julia> findn(A)
([1, 1, 3, 2], [1, 2, 2, 3])
julia> A = zeros(2,2)
2×2 Array{Float64,2}:
0.0 0.0
0.0 0.0
julia> findn(A)
(Int64[], Int64[])
Base.findnz
— Function.findnz(A)
Return a tuple (I, J, V)
where I
and J
are the row and column indexes of the non-zero values in matrix A
, and V
is a vector of the non-zero values.
julia> A = [1 2 0; 0 0 3; 0 4 0]
3×3 Array{Int64,2}:
1 2 0
0 0 3
0 4 0
julia> findnz(A)
([1, 1, 3, 2], [1, 2, 2, 3], [1, 2, 4, 3])
Base.findfirst
— Method.findfirst(A)
Return the linear index of the first non-zero value in A
(determined by A[i]!=0
). Returns 0
if no such value is found.
julia> A = [0 0; 1 0]
2×2 Array{Int64,2}:
0 0
1 0
julia> findfirst(A)
2
Base.findfirst
— Method.findfirst(A, v)
Return the linear index of the first element equal to v
in A
. Returns 0
if v
is not found.
julia> A = [4 6; 2 2]
2×2 Array{Int64,2}:
4 6
2 2
julia> findfirst(A,2)
2
julia> findfirst(A,3)
0
Base.findfirst
— Method.findfirst(predicate::Function, A)
Return the linear index of the first element of A
for which predicate
returns true
. Returns 0
if there is no such element.
julia> A = [1 4; 2 2]
2×2 Array{Int64,2}:
1 4
2 2
julia> findfirst(iseven, A)
2
julia> findfirst(x -> x>10, A)
0
Base.findlast
— Method.findlast(A)
Return the linear index of the last non-zero value in A
(determined by A[i]!=0
). Returns 0
if there is no non-zero value in A
.
julia> A = [1 0; 1 0]
2×2 Array{Int64,2}:
1 0
1 0
julia> findlast(A)
2
julia> A = zeros(2,2)
2×2 Array{Float64,2}:
0.0 0.0
0.0 0.0
julia> findlast(A)
0
Base.findlast
— Method.findlast(A, v)
Return the linear index of the last element equal to v
in A
. Returns 0
if there is no element of A
equal to v
.
julia> A = [1 2; 2 1]
2×2 Array{Int64,2}:
1 2
2 1
julia> findlast(A,1)
4
julia> findlast(A,2)
3
julia> findlast(A,3)
0
Base.findlast
— Method.findlast(predicate::Function, A)
Return the linear index of the last element of A
for which predicate
returns true
. Returns 0
if there is no such element.
julia> A = [1 2; 3 4]
2×2 Array{Int64,2}:
1 2
3 4
julia> findlast(isodd, A)
2
julia> findlast(x -> x > 5, A)
0
Base.findnext
— Method.findnext(A, i::Integer)
Find the next linear index >= i
of a non-zero element of A
, or 0
if not found.
julia> A = [0 0; 1 0]
2×2 Array{Int64,2}:
0 0
1 0
julia> findnext(A,1)
2
julia> findnext(A,3)
0
Base.findnext
— Method.findnext(predicate::Function, A, i::Integer)
Find the next linear index >= i
of an element of A
for which predicate
returns true
, or 0
if not found.
julia> A = [1 4; 2 2]
2×2 Array{Int64,2}:
1 4
2 2
julia> findnext(isodd, A, 1)
1
julia> findnext(isodd, A, 2)
0
Base.findnext
— Method.findnext(A, v, i::Integer)
Find the next linear index >= i
of an element of A
equal to v
(using ==
), or 0
if not found.
julia> A = [1 4; 2 2]
2×2 Array{Int64,2}:
1 4
2 2
julia> findnext(A,4,4)
0
julia> findnext(A,4,3)
3
Base.findprev
— Method.findprev(A, i::Integer)
Find the previous linear index <= i
of a non-zero element of A
, or 0
if not found.
julia> A = [0 0; 1 2]
2×2 Array{Int64,2}:
0 0
1 2
julia> findprev(A,2)
2
julia> findprev(A,1)
0
Base.findprev
— Method.findprev(predicate::Function, A, i::Integer)
Find the previous linear index <= i
of an element of A
for which predicate
returns true
, or 0
if not found.
julia> A = [4 6; 1 2]
2×2 Array{Int64,2}:
4 6
1 2
julia> findprev(isodd, A, 1)
0
julia> findprev(isodd, A, 3)
2
Base.findprev
— Method.findprev(A, v, i::Integer)
Find the previous linear index <= i
of an element of A
equal to v
(using ==
), or 0
if not found.
julia> A = [0 0; 1 2]
2×2 Array{Int64,2}:
0 0
1 2
julia> findprev(A, 1, 4)
2
julia> findprev(A, 1, 1)
0
Base.permutedims
— Function.permutedims(A, perm)
Permute the dimensions of array A
. perm
is a vector specifying a permutation of length ndims(A)
. This is a generalization of transpose for multi-dimensional arrays. Transpose is equivalent to permutedims(A, [2,1])
.
See also: PermutedDimsArray
.
julia> A = reshape(collect(1:8), (2,2,2))
2×2×2 Array{Int64,3}:
[:, :, 1] =
1 3
2 4
[:, :, 2] =
5 7
6 8
julia> permutedims(A, [3, 2, 1])
2×2×2 Array{Int64,3}:
[:, :, 1] =
1 3
5 7
[:, :, 2] =
2 4
6 8
Base.permutedims!
— Function.permutedims!(dest, src, perm)
Permute the dimensions of array src
and store the result in the array dest
. perm
is a vector specifying a permutation of length ndims(src)
. The preallocated array dest
should have size(dest) == size(src)[perm]
and is completely overwritten. No in-place permutation is supported and unexpected results will happen if src
and dest
have overlapping memory regions.
PermutedDimsArray(A, perm) -> B
Given an AbstractArray A
, create a view B
such that the dimensions appear to be permuted. Similar to permutedims
, except that no copying occurs (B
shares storage with A
).
See also: permutedims
.
Example
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
— Function.promote_shape(s1, s2)
Check two array shapes for compatibility, allowing trailing singleton dimensions, and return whichever shape has more dimensions.
julia> a = ones(3,4,1,1,1);
julia> b = ones(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)
Array functions
Base.accumulate
— Method.accumulate(op, A, dim=1)
Cumulative operation op
along a dimension dim
(defaults to 1). See also accumulate!
to use a preallocated output array, both for performance and to control the precision of the output (e.g. to avoid overflow). For common operations there are specialized variants of accumulate
, see: cumsum
, cumprod
julia> accumulate(+, [1,2,3])
3-element Array{Int64,1}:
1
3
6
julia> accumulate(*, [1,2,3])
3-element Array{Int64,1}:
1
2
6
accumulate(op, v0, A)
Like accumulate
, but using a starting element v0
. The first entry of the result will be op(v0, first(A))
. For example:
julia> accumulate(+, 100, [1,2,3])
3-element Array{Int64,1}:
101
103
106
julia> accumulate(min, 0, [1,2,-1])
3-element Array{Int64,1}:
0
0
-1
Base.accumulate!
— Function.accumulate!(op, B, A, dim=1)
Cumulative operation op
on A
along a dimension, storing the result in B
. The dimension defaults to 1. See also accumulate
.
Base.cumprod
— Function.cumprod(A, dim=1)
Cumulative product along a dimension dim
(defaults to 1). See also cumprod!
to use a preallocated output array, both for performance and to control the precision of the output (e.g. to avoid overflow).
julia> a = [1 2 3; 4 5 6]
2×3 Array{Int64,2}:
1 2 3
4 5 6
julia> cumprod(a,1)
2×3 Array{Int64,2}:
1 2 3
4 10 18
julia> cumprod(a,2)
2×3 Array{Int64,2}:
1 2 6
4 20 120
Base.cumprod!
— Function.cumprod!(B, A, dim::Integer=1)
Cumulative product of A
along a dimension, storing the result in B
. The dimension defaults to 1. See also cumprod
.
Base.cumsum
— Function.cumsum(A, dim=1)
Cumulative sum along a dimension dim
(defaults to 1). See also cumsum!
to use a preallocated output array, both for performance and to control the precision of the output (e.g. to avoid overflow).
julia> a = [1 2 3; 4 5 6]
2×3 Array{Int64,2}:
1 2 3
4 5 6
julia> cumsum(a,1)
2×3 Array{Int64,2}:
1 2 3
5 7 9
julia> cumsum(a,2)
2×3 Array{Int64,2}:
1 3 6
4 9 15
Base.cumsum!
— Function.cumsum!(B, A, dim::Integer=1)
Cumulative sum of A
along a dimension, storing the result in B
. The dimension defaults to 1. See also cumsum
.
Base.cumsum_kbn
— Function.cumsum_kbn(A, [dim::Integer=1])
Cumulative sum along a dimension, using the Kahan-Babuska-Neumaier compensated summation algorithm for additional accuracy. The dimension defaults to 1.
Base.LinAlg.diff
— Function.diff(A, [dim::Integer=1])
Finite difference operator of matrix or vector A
. If A
is a matrix, compute the finite difference over a dimension dim
(default 1
).
Example
julia> a = [2 4; 6 16]
2×2 Array{Int64,2}:
2 4
6 16
julia> diff(a,2)
2×1 Array{Int64,2}:
2
10
Base.LinAlg.gradient
— Function.gradient(F::AbstractVector, [h::Real])
Compute differences along vector F
, using h
as the spacing between points. The default spacing is one.
Example
julia> a = [2,4,6,8];
julia> gradient(a)
4-element Array{Float64,1}:
2.0
2.0
2.0
2.0
Base.rot180
— Function.rot180(A)
Rotate matrix A
180 degrees.
julia> a = [1 2; 3 4]
2×2 Array{Int64,2}:
1 2
3 4
julia> rot180(a)
2×2 Array{Int64,2}:
4 3
2 1
rot180(A, k)
Rotate matrix A
180 degrees an integer k
number of times. If k
is even, this is equivalent to a copy
.
julia> a = [1 2; 3 4]
2×2 Array{Int64,2}:
1 2
3 4
julia> rot180(a,1)
2×2 Array{Int64,2}:
4 3
2 1
julia> rot180(a,2)
2×2 Array{Int64,2}:
1 2
3 4
Base.rotl90
— Function.rotl90(A)
Rotate matrix A
left 90 degrees.
julia> a = [1 2; 3 4]
2×2 Array{Int64,2}:
1 2
3 4
julia> rotl90(a)
2×2 Array{Int64,2}:
2 4
1 3
rotl90(A, k)
Rotate matrix A
left 90 degrees an integer k
number of times. If k
is zero or a multiple of four, this is equivalent to a copy
.
julia> a = [1 2; 3 4]
2×2 Array{Int64,2}:
1 2
3 4
julia> rotl90(a,1)
2×2 Array{Int64,2}:
2 4
1 3
julia> rotl90(a,2)
2×2 Array{Int64,2}:
4 3
2 1
julia> rotl90(a,3)
2×2 Array{Int64,2}:
3 1
4 2
julia> rotl90(a,4)
2×2 Array{Int64,2}:
1 2
3 4
Base.rotr90
— Function.rotr90(A)
Rotate matrix A
right 90 degrees.
julia> a = [1 2; 3 4]
2×2 Array{Int64,2}:
1 2
3 4
julia> rotr90(a)
2×2 Array{Int64,2}:
3 1
4 2
rotr90(A, k)
Rotate matrix A
right 90 degrees an integer k
number of times. If k
is zero or a multiple of four, this is equivalent to a copy
.
julia> a = [1 2; 3 4]
2×2 Array{Int64,2}:
1 2
3 4
julia> rotr90(a,1)
2×2 Array{Int64,2}:
3 1
4 2
julia> rotr90(a,2)
2×2 Array{Int64,2}:
4 3
2 1
julia> rotr90(a,3)
2×2 Array{Int64,2}:
2 4
1 3
julia> rotr90(a,4)
2×2 Array{Int64,2}:
1 2
3 4
Base.reducedim
— Function.reducedim(f, A, region[, v0])
Reduce 2-argument function f
along dimensions of A
. region
is a vector specifying the dimensions to reduce, and v0
is the initial value to use in the reductions. For +
, *
, max
and min
the v0
argument is optional.
The associativity of the reduction is implementation-dependent; if you need a particular associativity, e.g. left-to-right, you should write your own loop. See documentation for reduce
.
julia> a = reshape(collect(1:16), (4,4))
4×4 Array{Int64,2}:
1 5 9 13
2 6 10 14
3 7 11 15
4 8 12 16
julia> reducedim(max, a, 2)
4×1 Array{Int64,2}:
13
14
15
16
julia> reducedim(max, a, 1)
1×4 Array{Int64,2}:
4 8 12 16
Base.mapreducedim
— Function.mapreducedim(f, op, A, region[, v0])
Evaluates to the same as reducedim(op, map(f, A), region, f(v0))
, but is generally faster because the intermediate array is avoided.
julia> a = reshape(collect(1:16), (4,4))
4×4 Array{Int64,2}:
1 5 9 13
2 6 10 14
3 7 11 15
4 8 12 16
julia> mapreducedim(isodd, *, a, 1)
1×4 Array{Bool,2}:
false false false false
julia> mapreducedim(isodd, |, a, 1, true)
1×4 Array{Bool,2}:
true true true true
Base.mapslices
— Function.mapslices(f, A, dims)
Transform the given dimensions of array A
using function f
. f
is called on each slice of A
of the form A[...,:,...,:,...]
. dims
is an integer vector specifying where the colons go in this expression. The results are concatenated along the remaining dimensions. For example, if dims
is [1,2]
and A
is 4-dimensional, f
is called on A[:,:,i,j]
for all i
and j
.
julia> a = reshape(collect(1:16),(2,2,2,2))
2×2×2×2 Array{Int64,4}:
[:, :, 1, 1] =
1 3
2 4
[:, :, 2, 1] =
5 7
6 8
[:, :, 1, 2] =
9 11
10 12
[:, :, 2, 2] =
13 15
14 16
julia> mapslices(sum, a, [1,2])
1×1×2×2 Array{Int64,4}:
[:, :, 1, 1] =
10
[:, :, 2, 1] =
26
[:, :, 1, 2] =
42
[:, :, 2, 2] =
58
Base.sum_kbn
— Function.sum_kbn(A)
Returns the sum of all elements of A
, using the Kahan-Babuska-Neumaier compensated summation algorithm for additional accuracy.
Combinatorics
Base.Random.randperm
— Function.randperm([rng=GLOBAL_RNG,] n::Integer)
Construct a random permutation of length n
. The optional rng
argument specifies a random number generator (see Random Numbers). To randomly permute a arbitrary vector, see shuffle
or shuffle!
.
Base.invperm
— Function.invperm(v)
Return the inverse permutation of v
. If B = A[v]
, then A == B[invperm(v)]
.
julia> v = [2; 4; 3; 1];
julia> invperm(v)
4-element Array{Int64,1}:
4
1
3
2
julia> A = ['a','b','c','d'];
julia> B = A[v]
4-element Array{Char,1}:
'b'
'd'
'c'
'a'
julia> B[invperm(v)]
4-element Array{Char,1}:
'a'
'b'
'c'
'd'
Base.isperm
— Function.isperm(v) -> Bool
Returns true
if v
is a valid permutation.
julia> isperm([1; 2])
true
julia> isperm([1; 3])
false
Base.permute!
— Method.permute!(v, p)
Permute vector v
in-place, according to permutation p
. No checking is done to verify that p
is a permutation.
To return a new permutation, use v[p]
. Note that this is generally faster than permute!(v,p)
for large vectors.
See also ipermute!
julia> A = [1, 1, 3, 4];
julia> perm = [2, 4, 3, 1];
julia> permute!(A, perm);
julia> A
4-element Array{Int64,1}:
1
4
3
1
Base.ipermute!
— Function.ipermute!(v, p)
Like permute!
, but the inverse of the given permutation is applied.
julia> A = [1, 1, 3, 4];
julia> perm = [2, 4, 3, 1];
julia> ipermute!(A, perm);
julia> A
4-element Array{Int64,1}:
4
1
3
1
Base.Random.randcycle
— Function.randcycle([rng=GLOBAL_RNG,] n::Integer)
Construct a random cyclic permutation of length n
. The optional rng
argument specifies a random number generator, see Random Numbers.
Base.Random.shuffle
— Function.shuffle([rng=GLOBAL_RNG,] v)
Return a randomly permuted copy of v
. The optional rng
argument specifies a random number generator (see Random Numbers). To permute v
in-place, see shuffle!
. To obtain randomly permuted indices, see randperm
.
Base.Random.shuffle!
— Function.shuffle!([rng=GLOBAL_RNG,] v)
In-place version of shuffle
: randomly permute the array v
in-place, optionally supplying the random-number generator rng
.
Base.reverse
— Function.reverse(v [, start=1 [, stop=length(v) ]] )
Return a copy of v
reversed from start to stop.
Base.reverseind
— Function.reverseind(v, i)
Given an index i
in reverse(v)
, return the corresponding index in v
so that v[reverseind(v,i)] == reverse(v)[i]
. (This can be nontrivial in the case where v
is a Unicode string.)
Base.reverse!
— Function.reverse!(v [, start=1 [, stop=length(v) ]]) -> v
In-place version of reverse
.
BitArrays
BitArray
s are space-efficient "packed" boolean arrays, which store one bit per boolean value. They can be used similarly to Array{Bool}
arrays (which store one byte per boolean value), and can be converted to/from the latter via Array(bitarray)
and BitArray(array)
, respectively.
Base.flipbits!
— Function.flipbits!(B::BitArray{N}) -> BitArray{N}
Performs a bitwise not operation on B
. See ~
.
julia> A = trues(2,2)
2×2 BitArray{2}:
true true
true true
julia> flipbits!(A)
2×2 BitArray{2}:
false false
false false
Base.rol!
— Function.rol!(dest::BitVector, src::BitVector, i::Integer) -> BitVector
Performs a left rotation operation on src
and puts the result into dest
. i
controls how far to rotate the bits.
rol!(B::BitVector, i::Integer) -> BitVector
Performs a left rotation operation in-place on B
. i
controls how far to rotate the bits.
Base.rol
— Function.rol(B::BitVector, i::Integer) -> BitVector
Performs a left rotation operation, returning a new BitVector
. i
controls how far to rotate the bits. See also rol!
.
julia> A = BitArray([true, true, false, false, true])
5-element BitArray{1}:
true
true
false
false
true
julia> rol(A,1)
5-element BitArray{1}:
true
false
false
true
true
julia> rol(A,2)
5-element BitArray{1}:
false
false
true
true
true
julia> rol(A,5)
5-element BitArray{1}:
true
true
false
false
true
Base.ror!
— Function.ror!(dest::BitVector, src::BitVector, i::Integer) -> BitVector
Performs a right rotation operation on src
and puts the result into dest
. i
controls how far to rotate the bits.
ror!(B::BitVector, i::Integer) -> BitVector
Performs a right rotation operation in-place on B
. i
controls how far to rotate the bits.
Base.ror
— Function.ror(B::BitVector, i::Integer) -> BitVector
Performs a right rotation operation on B
, returning a new BitVector
. i
controls how far to rotate the bits. See also ror!
.
julia> A = BitArray([true, true, false, false, true])
5-element BitArray{1}:
true
true
false
false
true
julia> ror(A,1)
5-element BitArray{1}:
true
true
true
false
false
julia> ror(A,2)
5-element BitArray{1}:
false
true
true
true
false
julia> ror(A,5)
5-element BitArray{1}:
true
true
false
false
true
Sparse Vectors and Matrices
Sparse vectors and matrices largely support the same set of operations as their dense counterparts. The following functions are specific to sparse arrays.
Base.SparseArrays.sparse
— Function.sparse(A)
Convert an AbstractMatrix A
into a sparse matrix.
julia> A = eye(3)
3×3 Array{Float64,2}:
1.0 0.0 0.0
0.0 1.0 0.0
0.0 0.0 1.0
julia> sparse(A)
3×3 SparseMatrixCSC{Float64,Int64} with 3 stored entries:
[1, 1] = 1.0
[2, 2] = 1.0
[3, 3] = 1.0
sparse(I, J, V,[ m, n, combine])
Create a sparse matrix S
of dimensions m x n
such that S[I[k], J[k]] = V[k]
. The combine
function is used to combine duplicates. If m
and n
are not specified, they are set to maximum(I)
and maximum(J)
respectively. If the combine
function is not supplied, combine
defaults to +
unless the elements of V
are Booleans in which case combine
defaults to |
. All elements of I
must satisfy 1 <= I[k] <= m
, and all elements of J
must satisfy 1 <= J[k] <= n
. Numerical zeros in (I
, J
, V
) are retained as structural nonzeros; to drop numerical zeros, use dropzeros!
.
For additional documentation and an expert driver, see Base.SparseArrays.sparse!
.
julia> Is = [1; 2; 3];
julia> Js = [1; 2; 3];
julia> Vs = [1; 2; 3];
julia> sparse(Is, Js, Vs)
3×3 SparseMatrixCSC{Int64,Int64} with 3 stored entries:
[1, 1] = 1
[2, 2] = 2
[3, 3] = 3
Base.SparseArrays.sparsevec
— Function.sparsevec(I, V, [m, combine])
Create a sparse vector S
of length m
such that S[I[k]] = V[k]
. Duplicates are combined using the combine
function, which defaults to +
if no combine
argument is provided, unless the elements of V
are Booleans in which case combine
defaults to |
.
julia> II = [1, 3, 3, 5]; V = [0.1, 0.2, 0.3, 0.2];
julia> sparsevec(II, V)
5-element SparseVector{Float64,Int64} with 3 stored entries:
[1] = 0.1
[3] = 0.5
[5] = 0.2
julia> sparsevec(II, V, 8, -)
8-element SparseVector{Float64,Int64} with 3 stored entries:
[1] = 0.1
[3] = -0.1
[5] = 0.2
julia> sparsevec([1, 3, 1, 2, 2], [true, true, false, false, false])
3-element SparseVector{Bool,Int64} with 3 stored entries:
[1] = true
[2] = false
[3] = true
sparsevec(d::Dict, [m])
Create a sparse vector of length m
where the nonzero indices are keys from the dictionary, and the nonzero values are the values from the dictionary.
julia> sparsevec(Dict(1 => 3, 2 => 2))
2-element SparseVector{Int64,Int64} with 2 stored entries:
[1] = 3
[2] = 2
sparsevec(A)
Convert a vector A
into a sparse vector of length m
.
julia> sparsevec([1.0, 2.0, 0.0, 0.0, 3.0, 0.0])
6-element SparseVector{Float64,Int64} with 3 stored entries:
[1] = 1.0
[2] = 2.0
[5] = 3.0
Base.SparseArrays.issparse
— Function.issparse(S)
Returns true
if S
is sparse, and false
otherwise.
Base.full
— Function.full(S)
Convert a sparse matrix or vector S
into a dense matrix or vector.
julia> A = speye(3)
3×3 SparseMatrixCSC{Float64,Int64} with 3 stored entries:
[1, 1] = 1.0
[2, 2] = 1.0
[3, 3] = 1.0
julia> full(A)
3×3 Array{Float64,2}:
1.0 0.0 0.0
0.0 1.0 0.0
0.0 0.0 1.0
Base.SparseArrays.nnz
— Function.nnz(A)
Returns the number of stored (filled) elements in a sparse array.
julia> A = speye(3)
3×3 SparseMatrixCSC{Float64,Int64} with 3 stored entries:
[1, 1] = 1.0
[2, 2] = 1.0
[3, 3] = 1.0
julia> nnz(A)
3
Base.SparseArrays.spzeros
— Function.spzeros([type,]m[,n])
Create a sparse vector of length m
or sparse matrix of size m x n
. This sparse array will not contain any nonzero values. No storage will be allocated for nonzero values during construction. The type defaults to Float64
if not specified.
julia> spzeros(3, 3)
3×3 SparseMatrixCSC{Float64,Int64} with 0 stored entries
julia> spzeros(Float32, 4)
4-element SparseVector{Float32,Int64} with 0 stored entries
Base.SparseArrays.spones
— Function.spones(S)
Create a sparse array with the same structure as that of S
, but with every nonzero element having the value 1.0
.
julia> A = sparse([1,2,3,4],[2,4,3,1],[5.,4.,3.,2.])
4×4 SparseMatrixCSC{Float64,Int64} with 4 stored entries:
[4, 1] = 2.0
[1, 2] = 5.0
[3, 3] = 3.0
[2, 4] = 4.0
julia> spones(A)
4×4 SparseMatrixCSC{Float64,Int64} with 4 stored entries:
[4, 1] = 1.0
[1, 2] = 1.0
[3, 3] = 1.0
[2, 4] = 1.0
Note the difference from speye
.
Base.SparseArrays.speye
— Method.speye([type,]m[,n])
Create a sparse identity matrix of size m x m
. When n
is supplied, create a sparse identity matrix of size m x n
. The type defaults to Float64
if not specified.
sparse(I, m, n)
is equivalent to speye(Int, m, n)
, and sparse(α*I, m, n)
can be used to efficiently create a sparse multiple α
of the identity matrix.
Base.SparseArrays.speye
— Method.speye(S)
Create a sparse identity matrix with the same size as S
.
julia> A = sparse([1,2,3,4],[2,4,3,1],[5.,4.,3.,2.])
4×4 SparseMatrixCSC{Float64,Int64} with 4 stored entries:
[4, 1] = 2.0
[1, 2] = 5.0
[3, 3] = 3.0
[2, 4] = 4.0
julia> speye(A)
4×4 SparseMatrixCSC{Float64,Int64} with 4 stored entries:
[1, 1] = 1.0
[2, 2] = 1.0
[3, 3] = 1.0
[4, 4] = 1.0
Note the difference from spones
.
speye([type,]m[,n])
Create a sparse identity matrix of size m x m
. When n
is supplied, create a sparse identity matrix of size m x n
. The type defaults to Float64
if not specified.
sparse(I, m, n)
is equivalent to speye(Int, m, n)
, and sparse(α*I, m, n)
can be used to efficiently create a sparse multiple α
of the identity matrix.
Base.SparseArrays.spdiagm
— Function.spdiagm(B, d[, m, n])
Construct a sparse diagonal matrix. B
is a tuple of vectors containing the diagonals and d
is a tuple containing the positions of the diagonals. In the case the input contains only one diagonal, B
can be a vector (instead of a tuple) and d
can be the diagonal position (instead of a tuple), defaulting to 0 (diagonal). Optionally, m
and n
specify the size of the resulting sparse matrix.
julia> spdiagm(([1,2,3,4],[4,3,2,1]),(-1,1))
5×5 SparseMatrixCSC{Int64,Int64} with 8 stored entries:
[2, 1] = 1
[1, 2] = 4
[3, 2] = 2
[2, 3] = 3
[4, 3] = 3
[3, 4] = 2
[5, 4] = 4
[4, 5] = 1
Base.SparseArrays.sprand
— Function.sprand([rng],[type],m,[n],p::AbstractFloat,[rfn])
Create a random length m
sparse vector or m
by n
sparse matrix, in which the probability of any element being nonzero is independently given by p
(and hence the mean density of nonzeros is also exactly p
). Nonzero values are sampled from the distribution specified by rfn
and have the type type
. The uniform distribution is used in case rfn
is not specified. The optional rng
argument specifies a random number generator, see Random Numbers.
julia> rng = MersenneTwister(1234);
julia> sprand(rng, Bool, 2, 2, 0.5)
2×2 SparseMatrixCSC{Bool,Int64} with 2 stored entries:
[1, 1] = true
[2, 1] = true
julia> sprand(rng, Float64, 3, 0.75)
3-element SparseVector{Float64,Int64} with 1 stored entry:
[3] = 0.298614
Base.SparseArrays.sprandn
— Function.sprandn([rng], m[,n],p::AbstractFloat)
Create a random sparse vector of length m
or sparse matrix of size m
by n
with the specified (independent) probability p
of any entry being nonzero, where nonzero values are sampled from the normal distribution. The optional rng
argument specifies a random number generator, see Random Numbers.
julia> rng = MersenneTwister(1234);
julia> sprandn(rng, 2, 2, 0.75)
2×2 SparseMatrixCSC{Float64,Int64} with 3 stored entries:
[1, 1] = 0.532813
[2, 1] = -0.271735
[2, 2] = 0.502334
Base.SparseArrays.nonzeros
— Function.nonzeros(A)
Return a vector of the structural nonzero values in sparse array A
. This includes zeros that are explicitly stored in the sparse array. The returned vector points directly to the internal nonzero storage of A
, and any modifications to the returned vector will mutate A
as well. See rowvals
and nzrange
.
julia> A = speye(3)
3×3 SparseMatrixCSC{Float64,Int64} with 3 stored entries:
[1, 1] = 1.0
[2, 2] = 1.0
[3, 3] = 1.0
julia> nonzeros(A)
3-element Array{Float64,1}:
1.0
1.0
1.0
Base.SparseArrays.rowvals
— Function.rowvals(A::SparseMatrixCSC)
Return a vector of the row indices of A
. Any modifications to the returned vector will mutate A
as well. Providing access to how the row indices are stored internally can be useful in conjunction with iterating over structural nonzero values. See also nonzeros
and nzrange
.
julia> A = speye(3)
3×3 SparseMatrixCSC{Float64,Int64} with 3 stored entries:
[1, 1] = 1.0
[2, 2] = 1.0
[3, 3] = 1.0
julia> rowvals(A)
3-element Array{Int64,1}:
1
2
3
Base.SparseArrays.nzrange
— Function.nzrange(A::SparseMatrixCSC, col::Integer)
Return the range of indices to the structural nonzero values of a sparse matrix column. In conjunction with nonzeros
and rowvals
, this allows for convenient iterating over a sparse matrix :
A = sparse(I,J,V)
rows = rowvals(A)
vals = nonzeros(A)
m, n = size(A)
for i = 1:n
for j in nzrange(A, i)
row = rows[j]
val = vals[j]
# perform sparse wizardry...
end
end
Base.SparseArrays.dropzeros!
— Method.dropzeros!(A::SparseMatrixCSC, trim::Bool = true)
Removes stored numerical zeros from A
, optionally trimming resulting excess space from A.rowval
and A.nzval
when trim
is true
.
For an out-of-place version, see dropzeros
. For algorithmic information, see fkeep!
.
Base.SparseArrays.dropzeros
— Method.dropzeros(A::SparseMatrixCSC, trim::Bool = true)
Generates a copy of A
and removes stored numerical zeros from that copy, optionally trimming excess space from the result's rowval
and nzval
arrays when trim
is true
.
For an in-place version and algorithmic information, see dropzeros!
.
Base.SparseArrays.dropzeros!
— Method.dropzeros!(x::SparseVector, trim::Bool = true)
Removes stored numerical zeros from x
, optionally trimming resulting excess space from x.nzind
and x.nzval
when trim
is true
.
For an out-of-place version, see dropzeros
. For algorithmic information, see fkeep!
.
Base.SparseArrays.dropzeros
— Method.dropzeros(x::SparseVector, trim::Bool = true)
Generates a copy of x
and removes numerical zeros from that copy, optionally trimming excess space from the result's nzind
and nzval
arrays when trim
is true
.
For an in-place version and algorithmic information, see dropzeros!
.
Base.SparseArrays.permute
— Function.permute{Tv,Ti}(A::SparseMatrixCSC{Tv,Ti}, p::AbstractVector{<:Integer},
q::AbstractVector{<:Integer})
Bilaterally permute A
, returning PAQ
(A[p,q]
). Column-permutation q
's length must match A
's column count (length(q) == A.n
). Row-permutation p
's length must match A
's row count (length(p) == A.m
).
For expert drivers and additional information, see permute!
.
Base.permute!
— Method.permute!{Tv,Ti}(X::SparseMatrixCSC{Tv,Ti}, A::SparseMatrixCSC{Tv,Ti},
p::AbstractVector{<:Integer}, q::AbstractVector{<:Integer}[, C::SparseMatrixCSC{Tv,Ti}])
Bilaterally permute A
, storing result PAQ
(A[p,q]
) in X
. Stores intermediate result (AQ)^T
(transpose(A[:,q])
) in optional argument C
if present. Requires that none of X
, A
, and, if present, C
alias each other; to store result PAQ
back into A
, use the following method lacking X
:
permute!{Tv,Ti}(A::SparseMatrixCSC{Tv,Ti}, p::AbstractVector{<:Integer},
q::AbstractVector{<:Integer}[, C::SparseMatrixCSC{Tv,Ti}[, workcolptr::Vector{Ti}]])
X
's dimensions must match those of A
(X.m == A.m
and X.n == A.n
), and X
must have enough storage to accommodate all allocated entries in A
(length(X.rowval) >= nnz(A)
and length(X.nzval) >= nnz(A)
). Column-permutation q
's length must match A
's column count (length(q) == A.n
). Row-permutation p
's length must match A
's row count (length(p) == A.m
).
C
's dimensions must match those of transpose(A)
(C.m == A.n
and C.n == A.m
), and C
must have enough storage to accommodate all allocated entries in A
(length(C.rowval) >= nnz(A)
and length(C.nzval) >= nnz(A)
).
For additional (algorithmic) information, and for versions of these methods that forgo argument checking, see (unexported) parent methods unchecked_noalias_permute!
and unchecked_aliasing_permute!
.
See also: permute