Arrays¶
Basic functions¶
-
ndims
(A) → Integer¶ Returns the number of dimensions of A
-
size
(A)¶ Returns a tuple containing the dimensions of A
-
iseltype
(A, T)¶ Tests whether A or its elements are of type T
-
length
(A) → Integer¶ Returns the number of elements in A
-
countnz
(A)¶ 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.
-
conj!
(A)¶ Convert an array to its complex conjugate in-place
-
stride
(A, k)¶ Returns the distance in memory (in number of elements) between adjacent elements in dimension k
-
strides
(A)¶ Returns a tuple of the memory strides in each dimension
-
ind2sub
(dims, index) → subscripts¶ Returns a tuple of subscripts into an array with dimensions
dims
, corresponding to the linear indexindex
Example
i, j, ... = ind2sub(size(A), indmax(A))
provides the indices of the maximum element
-
sub2ind
(dims, i, j, k...) → index¶ The inverse of
ind2sub
, returns the linear index corresponding to the provided subscripts
Constructors¶
-
Array
(type, dims)¶ Construct an uninitialized dense array.
dims
may be a tuple or a series of integer arguments.
-
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 usingType[a,b,c,...]
.
-
cell
(dims)¶ Construct an uninitialized cell array (heterogeneous array).
dims
can be either a tuple or a series of integer arguments.
-
zeros
(type, dims)¶ Create an array of all zeros of specified type. The type defaults to Float64 if not specified.
-
zeros
(A) Create an array of all zeros with the same element type and shape as A.
-
ones
(type, dims)¶ Create an array of all ones of specified type. The type defaults to Float64 if not specified.
-
ones
(A) Create an array of all ones with the same element type and shape as A.
-
trues
(dims)¶ Create a
BitArray
with all values set to true
-
falses
(dims)¶ Create a
BitArray
with all values set to false
-
fill
(x, dims)¶ Create an array filled with the value
x
. For example,fill(1.0, (10,10))
returns a 10x10 array of floats, with each element initialized to 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 evaluatingFoo()
once.
-
fill!
(A, x)¶ Fill array
A
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.
-
reshape
(A, dims)¶ Create an array with the same data as the given array, but with different dimensions. An implementation for a particular type of array may choose whether the data is copied or shared.
-
similar
(array, element_type, dims)¶ Create an uninitialized array of the same type as the given array, but with the specified element type and dimensions. The second and third arguments are both optional. The
dims
argument may be a tuple or a series of integer arguments.
-
reinterpret
(type, A)¶ Change the type-interpretation of a block of memory. For example,
reinterpret(Float32, uint32(7))
interprets the 4 bytes corresponding touint32(7)
as aFloat32
. For arrays, this constructs an array with the same binary data as the given array, but with the specified element type.
-
eye
(n)¶ n-by-n identity matrix
-
eye
(m, n) m-by-n identity matrix
-
eye
(A) Constructs an identity matrix of the same dimensions and type as
A
.
-
linspace
(start, stop, n)¶ Construct a vector of
n
linearly-spaced elements fromstart
tostop
. See also:linrange()
that constructs a range object.
-
logspace
(start, stop, n)¶ Construct a vector of
n
logarithmically-spaced numbers from10^start
to10^stop
.
Mathematical operators and functions¶
All mathematical operations and functions are supported for arrays
-
broadcast
(f, As...)¶ Broadcasts the arrays
As
to a common size by expanding singleton dimensions, and returns an array of the resultsf(as...)
for each position.
-
broadcast!
(f, dest, As...)¶ Like
broadcast
, 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)
.
-
bitbroadcast
(f, As...)¶ Like
broadcast
, but allocates aBitArray
to store the result, rather then anArray
.
-
broadcast_function
(f)¶ Returns a function
broadcast_f
such thatbroadcast_function(f)(As...) === broadcast(f, As...)
. Most useful in the formconst broadcast_f = broadcast_function(f)
.
-
broadcast!_function
(f)¶ Like
broadcast_function
, but forbroadcast!
.
Indexing, Assignment, and Concatenation¶
-
getindex
(A, inds...) Returns a subset of array
A
as specified byinds
, where eachind
may be anInt
, aRange
, or aVector
.
-
sub
(A, inds...)¶ Returns a SubArray, which stores the input
A
andinds
rather than computing the result immediately. Callinggetindex
on a SubArray computes the indices on the fly.
-
parent
(A)¶ Returns the “parent array” of an array view type (e.g., SubArray), or the array itself if it is not a view
-
parentindexes
(A)¶ From an array view
A
, returns the corresponding indexes in the parent
-
slicedim
(A, d, i)¶ Return all the data of
A
where the index for dimensiond
equalsi
. Equivalent toA[:,:,...,i,:,:,...]
wherei
is in positiond
.
-
slice
(A, inds...)¶ Create a view of the given indexes of array
A
, dropping dimensions indexed with scalars.
-
setindex!
(A, X, inds...)¶ Store values from array
X
within some subset ofA
as specified byinds
.
-
broadcast_getindex
(A, inds...)¶ Broadcasts the
inds
arrays to a common size likebroadcast
, and returns an array of the resultsA[ks...]
, whereks
goes over the positions in the broadcast.
-
broadcast_setindex!
(A, X, inds...)¶ Broadcasts the
X
andinds
arrays to a common size and stores the value from each position inX
at the indices given by the same positions ininds
.
-
cat
(dim, A...)¶ Concatenate the input arrays along the specified dimension
-
vcat
(A...)¶ Concatenate along dimension 1
-
hcat
(A...)¶ Concatenate along dimension 2
-
hvcat
(rows::(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. For example,
[a b;c d e]
callshvcat((2,3),a,b,c,d,e)
.If the first argument is a single integer
n
, then all block rows are assumed to haven
block columns.
-
flipdim
(A, d)¶ Reverse
A
in dimensiond
.
-
flipud
(A)¶ Equivalent to
flipdim(A,1)
.
-
fliplr
(A)¶ Equivalent to
flipdim(A,2)
.
-
circshift
(A, shifts)¶ Circularly shift the data in an array. The second argument is a vector giving the amount to shift in each dimension.
-
find
(A)¶ Return a vector of the linear indexes of the non-zeros in
A
(determined byA[i]!=0
). A common use of this is to convert a boolean array to an array of indexes of thetrue
elements.
-
find
(f, A) Return a vector of the linear indexes of
A
wheref
returns true.
-
findn
(A)¶ Return a vector of indexes for each dimension giving the locations of the non-zeros in
A
(determined byA[i]!=0
).
-
findnz
(A)¶ Return a tuple
(I, J, V)
whereI
andJ
are the row and column indexes of the non-zero values in matrixA
, andV
is a vector of the non-zero values.
-
findfirst
(A)¶ Return the index of the first non-zero value in
A
(determined byA[i]!=0
).
-
findfirst
(A, v) Return the index of the first element equal to
v
inA
.
-
findfirst
(predicate, A) Return the index of the first element of
A
for whichpredicate
returns true.
-
findnext
(A, i)¶ Find the next index >=
i
of a non-zero element ofA
, or0
if not found.
-
findnext
(predicate, A, i) Find the next index >=
i
of an element ofA
for whichpredicate
returns true, or0
if not found.
-
findnext
(A, v, i) Find the next index >=
i
of an element ofA
equal tov
(using==
), or0
if not found.
-
permutedims
(A, perm)¶ Permute the dimensions of array
A
.perm
is a vector specifying a permutation of lengthndims(A)
. This is a generalization of transpose for multi-dimensional arrays. Transpose is equivalent topermutedims(A,[2,1])
.
-
ipermutedims
(A, perm)¶ Like
permutedims()
, except the inverse of the given permutation is applied.
-
squeeze
(A, dims)¶ Remove the dimensions specified by
dims
from arrayA
-
vec
(Array) → Vector¶ Vectorize an array using column-major convention.
-
promote_shape
(s1, s2)¶ Check two array shapes for compatibility, allowing trailing singleton dimensions, and return whichever shape has more dimensions.
-
checkbounds
(array, indexes...)¶ Throw an error if the specified indexes are not in bounds for the given array.
-
randsubseq
(A, p) → Vector¶ Return a vector consisting of a random subsequence of the given array
A
, where each element ofA
is included (in order) with independent probabilityp
. (Complexity is linear inp*length(A)
, so this function is efficient even ifp
is small andA
is large.) Technically, this process is known as “Bernoulli sampling” ofA
.
-
randsubseq!
(S, A, p)¶ Like
randsubseq
, but the results are stored inS
(which is resized as needed).
Array functions¶
-
cumprod
(A[, dim])¶ Cumulative product along a dimension.
-
cumprod!
(B, A[, dim])¶ Cumulative product of
A
along a dimension, storing the result inB
.
-
cumsum
(A[, dim])¶ Cumulative sum along a dimension.
-
cumsum!
(B, A[, dim])¶ Cumulative sum of
A
along a dimension, storing the result inB
.
-
cumsum_kbn
(A[, dim])¶ Cumulative sum along a dimension, using the Kahan-Babuska-Neumaier compensated summation algorithm for additional accuracy.
-
cummin
(A[, dim])¶ Cumulative minimum along a dimension.
-
cummax
(A[, dim])¶ Cumulative maximum along a dimension.
-
diff
(A[, dim])¶ Finite difference operator of matrix or vector.
-
gradient
(F[, h])¶ Compute differences along vector
F
, usingh
as the spacing between points. The default spacing is one.
-
rot180
(A)¶ Rotate matrix
A
180 degrees.
-
rot180
(A, k) Rotate matrix
A
180 degrees an integerk
number of times. Ifk
is even, this is equivalent to acopy
.
-
rotl90
(A)¶ Rotate matrix
A
left 90 degrees.
-
rotl90
(A, k) Rotate matrix
A
left 90 degrees an integerk
number of times. Ifk
is zero or a multiple of four, this is equivalent to acopy
.
-
rotr90
(A)¶ Rotate matrix
A
right 90 degrees.
-
rotr90
(A, k) Rotate matrix
A
right 90 degrees an integerk
number of times. Ifk
is zero or a multiple of four, this is equivalent to acopy
.
-
reducedim
(f, A, dims, initial)¶ Reduce 2-argument function
f
along dimensions ofA
.dims
is a vector specifying the dimensions to reduce, andinitial
is the initial value to use in the reductions.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
.
-
mapslices
(f, A, dims)¶ Transform the given dimensions of array
A
using functionf
.f
is called on each slice ofA
of the formA[...,:,...,:,...]
.dims
is an integer vector specifying where the colons go in this expression. The results are concatenated along the remaining dimensions. For example, ifdims
is[1,2]
and A is 4-dimensional,f
is called onA[:,:,i,j]
for alli
andj
.
-
sum_kbn
(A)¶ Returns the sum of all array elements, using the Kahan-Babuska-Neumaier compensated summation algorithm for additional accuracy.
-
cartesianmap
(f, dims)¶ Given a
dims
tuple of integers(m, n, ...)
, callf
on all combinations of integers in the ranges1:m
,1:n
, etc.julia> cartesianmap(println, (2,2)) 11 21 12 22
Combinatorics¶
-
nthperm
(v, k)¶ Compute the kth lexicographic permutation of a vector.
-
nthperm
(p) Return the
k
that generated permutationp
. Note thatnthperm(nthperm([1:n], k)) == k
for1 <= k <= factorial(n)
.
-
randperm
(n)¶ Construct a random permutation of the given length.
-
invperm
(v)¶ Return the inverse permutation of v.
-
isperm
(v) → Bool¶ Returns true if v is a valid permutation.
-
permute!
(v, p)¶ Permute vector
v
in-place, according to permutationp
. No checking is done to verify thatp
is a permutation.To return a new permutation, use
v[p]
. Note that this is generally faster thanpermute!(v,p)
for large vectors.
-
ipermute!
(v, p)¶ Like permute!, but the inverse of the given permutation is applied.
-
randcycle
(n)¶ Construct a random cyclic permutation of the given length.
-
shuffle
(v)¶ Return a randomly permuted copy of
v
.
-
reverse
(v[, start=1[, stop=length(v)]])¶ Return a copy of
v
reversed from start to stop.
-
combinations
(arr, n)¶ Generate all combinations of
n
elements from an indexable object. Because the number of combinations can be very large, this function returns an iterator object. Usecollect(combinations(a,n))
to get an array of all combinations.
-
permutations
(arr)¶ Generate all permutations of an indexable object. Because the number of permutations can be very large, this function returns an iterator object. Use
collect(permutations(a,n))
to get an array of all permutations.
-
partitions
(n)¶ Generate all integer arrays that sum to
n
. Because the number of partitions can be very large, this function returns an iterator object. Usecollect(partitions(n))
to get an array of all partitions. The number of partitions to generete can be efficiently computed usinglength(partitions(n))
.
-
partitions
(n, m) Generate all arrays of
m
integers that sum ton
. Because the number of partitions can be very large, this function returns an iterator object. Usecollect(partitions(n,m))
to get an array of all partitions. The number of partitions to generete can be efficiently computed usinglength(partitions(n,m))
.
-
partitions
(array) Generate all set partitions of the elements of an array, represented as arrays of arrays. Because the number of partitions can be very large, this function returns an iterator object. Use
collect(partitions(array))
to get an array of all partitions. The number of partitions to generete can be efficiently computed usinglength(partitions(array))
.
-
partitions
(array, m) Generate all set partitions of the elements of an array into exactly m subsets, represented as arrays of arrays. Because the number of partitions can be very large, this function returns an iterator object. Use
collect(partitions(array,m))
to get an array of all partitions. The number of partitions into m subsets is equal to the Stirling number of the second kind and can be efficiently computed usinglength(partitions(array,m))
.
BitArrays¶
-
bitpack
(A::AbstractArray{T, N}) → BitArray¶ Converts a numeric array to a packed boolean array
-
bitunpack
(B::BitArray{N}) → Array{Bool,N}¶ Converts a packed boolean array to an array of booleans
-
flipbits!
(B::BitArray{N}) → BitArray{N}¶ Performs a bitwise not operation on B. See ~ operator.
-
rol
(B::BitArray{1}, i::Integer) → BitArray{1}¶ Left rotation operator.
-
ror
(B::BitArray{1}, i::Integer) → BitArray{1}¶ Right rotation operator.
Sparse Matrices¶
Sparse matrices support much of the same set of operations as dense matrices. The following functions are specific to sparse matrices.
-
sparse
(I, J, V[, m, n, combine])¶ Create a sparse matrix
S
of dimensionsm x n
such thatS[I[k], J[k]] = V[k]
. Thecombine
function is used to combine duplicates. Ifm
andn
are not specified, they are set tomax(I)
andmax(J)
respectively. If thecombine
function is not supplied, duplicates are added by default.
-
sparsevec
(I, V[, m, combine])¶ Create a sparse matrix
S
of sizem x 1
such thatS[I[k]] = V[k]
. Duplicates are combined using thecombine
function, which defaults to+
if it is not provided. In julia, sparse vectors are really just sparse matrices with one column. Given Julia’s Compressed Sparse Columns (CSC) storage format, a sparse column matrix with one column is sparse, whereas a sparse row matrix with one row ends up being dense.
-
sparsevec
(D::Dict[, m]) Create a sparse matrix of size
m x 1
where the row values are keys from the dictionary, and the nonzero values are the values from the dictionary.
-
issparse
(S)¶ Returns
true
ifS
is sparse, andfalse
otherwise.
-
sparse
(A) Convert a dense matrix
A
into a sparse matrix.
-
sparsevec
(A) Convert a dense vector
A
into a sparse matrix of sizem x 1
. In julia, sparse vectors are really just sparse matrices with one column.
-
full
(S)¶ Convert a sparse matrix
S
into a dense matrix.
-
nnz
(A)¶ Returns the number of stored (filled) elements in a sparse matrix.
-
spzeros
(m, n)¶ Create an empty sparse matrix of size
m x n
.
-
spones
(S)¶ Create a sparse matrix with the same structure as that of
S
, but with every nonzero element having the value1.0
.
-
speye
(type, m[, n])¶ Create a sparse identity matrix of specified type of size
m x m
. In casen
is supplied, create a sparse identity matrix of sizem x n
.
-
spdiagm
(B, d[, m, n])¶ Construct a sparse diagonal matrix.
B
is a tuple of vectors containing the diagonals andd
is a tuple containing the positions of the diagonals. In the case the input contains only one diagonaly,B
can be a vector (instead of a tuple) andd
can be the diagonal position (instead of a tuple), defaulting to 0 (diagonal). Optionally,m
andn
specify the size of the resulting sparse matrix.
-
sprand
(m, n, p[, rng])¶ Create a random
m
byn
sparse matrix, in which the probability of any element being nonzero is independently given byp
(and hence the mean density of nonzeros is also exactlyp
). Nonzero values are sampled from the distribution specified byrng
. The uniform distribution is used in caserng
is not specified.
-
sprandn
(m, n, p)¶ Create a random
m
byn
sparse matrix with the specified (independent) probabilityp
of any entry being nonzero, where nonzero values are sampled from the normal distribution.
-
sprandbool
(m, n, p)¶ Create a random
m
byn
sparse boolean matrix with the specified (independent) probabilityp
of any entry beingtrue
.
-
etree
(A[, post])¶ Compute the elimination tree of a symmetric sparse matrix
A
fromtriu(A)
and, optionally, its post-ordering permutation.
-
symperm
(A, p)¶ Return the symmetric permutation of A, which is
A[p,p]
. A should be symmetric and sparse, where only the upper triangular part of the matrix is stored. This algorithm ignores the lower triangular part of the matrix. Only the upper triangular part of the result is returned as well.
-
nonzeros
(A)¶ Return a vector of the structural nonzero values in sparse matrix
A
. This includes zeros that are explicitly stored in the sparse matrix. The returned vector points directly to the internal nonzero storage ofA
, and any modifications to the returned vector will mutateA
as well.