Arrays¶
Basic functions¶
ndims(A) → Integer¶Returns the number of dimensions of
A
size(A[, 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=rand(2,3,4);julia>size(A,2)3julia>size(A,3,2)(4,3)
iseltype(A, T)¶Tests whether
Aor its elements are of typeT.
length(A) → Integer¶Returns the number of elements in
A.
eachindex(A...)¶Creates an iterable object for visiting each index of an AbstractArray
Ain an efficient manner. For array types that have opted into fast linear indexing (likeArray), this is simply the range1: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])2x3sparsematrixwith3Int64entries:[1,1]=1[2,1]=-5[1,3]=2julia>foriterineachindex(A)@showiter.I[1],iter.I[2]@showA[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
AbstractArrayargument,eachindexwill create an iterable object that is fast for all arguments (aUnitRangeif all inputs have fast linear indexing, a CartesianRange otherwise). If the arrays have different sizes and/or dimensionalities,eachindexreturns an iterable that spans the largest range along each dimension.
Base.linearindexing(A)¶linearindexingdefines how an AbstractArray most efficiently accesses its elements. IfBase.linearindexing(A)returnsBase.LinearFast(), this means that linear indexing with only one index is an efficient operation. If it instead returnsBase.LinearSlow()(by default), this means that the array intrinsically accesses its elements with indices specified for every dimension. Since converting a linear index to multiple indexing subscripts is typically very expensive, this provides a traits-based mechanism to enable efficient generic code for all array types.An abstract array subtype
MyArraythat wishes to opt into fast linear indexing behaviors should definelinearindexingin the type-domain:Base.linearindexing{T<:MyArray}(::Type{T})=Base.LinearFast()
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 usennz, 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
ind2sub(a, index) → subscriptsReturns a tuple of subscripts into array
acorresponding to the linear indexindex
sub2ind(dims, i, j, k...) → index¶The inverse of
ind2sub, returns the linear index corresponding to the provided subscripts
Constructors¶
Array(dims)¶Array{T}(dims)constructs an uninitialized dense array with element typeT.dimsmay be a tuple or a series of integer arguments. The syntaxArray(T,dims)is also available, but deprecated.
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).
dimscan 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
Float64if not specified.
ones(A)Create an array of all ones with the same element type and shape as
A.
trues(dims)¶Create a
BitArraywith all values set totrue.
trues(A)Create a
BitArraywith all values set totrueof the same shape asA.
falses(dims)¶Create a
BitArraywith all values set tofalse.
falses(A)Create a
BitArraywith all values set tofalseof the same shape asA.
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 to1.0.If
xis 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
Awith the valuex. Ifxis an object reference, all elements will refer to the same object.fill!(A,Foo())will returnAfilled 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=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
eltypeandsize. 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 uninitializedArray{Int,2}since ranges are neither mutable nor support 2 dimensions:julia>similar(1:10,1,4)1x4Array{Int64,2}:4419743872437441387244197438880
Conversely,
similar(trues(10,10),2)returns an uninitializedBitVectorwith two elements sinceBitArrays are both mutable and can support 1-dimensional arrays:julia>similar(trues(10,10),2)2-elementBitArray{1}:falsefalse
Since
BitArrays can only store elements of typeBool, however, if you request a different element type it will create a regularArrayinstead:julia>similar(falses(10),Float64,2,4)2x4Array{Float64,2}:2.18425e-3142.18425e-3142.18425e-3142.18425e-3142.18425e-3142.18425e-3142.18425e-3142.18425e-314
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-nidentity matrix
eye(m, n)m-by-nidentity matrix
eye(A)Constructs an identity matrix of the same dimensions and type as
A.
linspace(start, stop, n=100)¶Construct a range of
nlinearly spaced elements fromstarttostop.
logspace(start, stop, n=50)¶Construct a vector of
nlogarithmically spaced numbers from10^startto10^stop.
Mathematical operators and functions¶
All mathematical operations and functions are supported for arrays
broadcast(f, As...)¶Broadcasts the arrays
Asto 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 thedestarray. Note thatdestis only used to store the result, and does not supply arguments tofunless 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 aBitArrayto store the result, rather then anArray.
broadcast_function(f)¶Returns a function
broadcast_fsuch thatbroadcast_function(f)(As...)===broadcast(f,As...). Most useful in the formconstbroadcast_f=broadcast_function(f).
broadcast!_function(f)¶Like
broadcast_function, but forbroadcast!.
Indexing, Assignment, and Concatenation¶
getindex(A, inds...)Returns a subset of array
Aas specified byinds, where eachindmay be anInt, aRange, or aVector. See the manual section on array indexing for details.
sub(A, inds...)¶Like
getindex(), but returns a view into the parent arrayAwith the given indices instead of making a copy. Callinggetindex()orsetindex!()on the returnedSubArraycomputes the indices to the parent array on the fly without checking bounds.
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
Awhere the index for dimensiondequalsi. Equivalent toA[:,:,...,i,:,:,...]whereiis in positiond.
slice(A, inds...)¶Returns a view of array
Awith the given indices likesub(), but drops all dimensions indexed with scalars.
setindex!(A, X, inds...)¶Store values from array
Xwithin some subset ofAas specified byinds.
broadcast_getindex(A, inds...)¶Broadcasts the
indsarrays to a common size likebroadcast, and returns an array of the resultsA[ks...], whereksgoes over the positions in the broadcast.
broadcast_setindex!(A, X, inds...)¶Broadcasts the
Xandindsarrays to a common size and stores the value from each position inXat the indices given by the same positions ininds.
cat(dims, A...)¶Concatenate the input arrays along the specified dimensions in the iterable
dims. For dimensions not indims, all input arrays should have the same size, which will also be the size of the output array along that dimension. For dimensions indims, the size of the output array is the sum of the sizes of the input arrays along that dimension. Ifdimsis a single number, the different arrays are tightly stacked along that dimension. Ifdimsis 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 withmatrices[1],matrices[2], ... as diagonal blocks and matching zero blocks away from the diagonal.
vcat(A...)¶Concatenate along dimension 1
hcat(A...)¶Concatenate along dimension 2
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>[abc;def]2x3Array{Int64,2}:123456julia>hvcat((3,3),a,b,c,d,e,f)2x3Array{Int64,2}:123456julia>[ab;cd;ef]3x2Array{Int64,2}:123456julia>hvcat((2,2,2),a,b,c,d,e,f)3x2Array{Int64,2}:123456
If the first argument is a single integer
n, then all block rows are assumed to havenblock columns.
flipdim(A, d)¶Reverse
Ain dimensiond.
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 thetrueelements.
find(f, A)Return a vector of the linear indexes of
Awherefreturnstrue.
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)whereIandJare the row and column indexes of the non-zero values in matrixA, andVis 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
vinA.
findfirst(predicate, A)Return the index of the first element of
Afor whichpredicatereturnstrue.
findlast(A)¶Return the index of the last non-zero value in
A(determined byA[i]!=0).
findlast(A, v)Return the index of the last element equal to
vinA.
findlast(predicate, A)Return the index of the last element of
Afor whichpredicatereturnstrue.
findnext(A, i)¶Find the next index >=
iof a non-zero element ofA, or0if not found.
findnext(predicate, A, i)Find the next index >=
iof an element ofAfor whichpredicatereturnstrue, or0if not found.
findnext(A, v, i)Find the next index >=
iof an element ofAequal tov(using==), or0if not found.
findprev(A, i)¶Find the previous index <=
iof a non-zero element ofA, or0if not found.
findprev(predicate, A, i)Find the previous index <=
iof an element ofAfor whichpredicatereturnstrue, or0if not found.
findprev(A, v, i)Find the previous index <=
iof an element ofAequal tov(using==), or0if not found.
permutedims(A, perm)¶Permute the dimensions of array
A.permis 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.
permutedims!(dest, src, perm)¶Permute the dimensions of array
srcand store the result in the arraydest.permis a vector specifying a permutation of lengthndims(src). The preallocated arraydestshould havesize(dest)==size(src)[perm]and is completely overwritten. No in-place permutation is supported and unexpected results will happen ifsrcanddesthave overlapping memory regions.
squeeze(A, dims)¶Remove the dimensions specified by
dimsfrom arrayA. Elements ofdimsmust be unique and within the range1:ndims(A).
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. Subtypes of
AbstractArrayshould specialize this method if they need to provide custom bounds checking behaviors.
checkbounds(::Type{Bool}, dimlength::Integer, index)Return a
Booldescribing if the given index is within the bounds of the given dimension length. 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.
randsubseq(A, p) → Vector¶Return a vector consisting of a random subsequence of the given array
A, where each element ofAis included (in order) with independent probabilityp. (Complexity is linear inp*length(A), so this function is efficient even ifpis small andAis 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
dim(defaults to 1). See alsocumprod!()to use a preallocated output array, both for performance and to control the precision of the output (e.g. to avoid overflow).
cumprod!(B, A[, dim])¶Cumulative product of
Aalong a dimension, storing the result inB. The dimension defaults to 1.
cumsum(A[, dim])¶Cumulative sum along a dimension
dim(defaults to 1). See alsocumsum!()to use a preallocated output array, both for performance and to control the precision of the output (e.g. to avoid overflow).
cumsum!(B, A[, dim])¶Cumulative sum of
Aalong a dimension, storing the result inB. The dimension defaults to 1.
cumsum_kbn(A[, dim])¶Cumulative sum along a dimension, using the Kahan-Babuska-Neumaier compensated summation algorithm for additional accuracy. The dimension defaults to 1.
cummin(A[, dim])¶Cumulative minimum along a dimension. The dimension defaults to 1.
cummax(A[, dim])¶Cumulative maximum along a dimension. The dimension defaults to 1.
diff(A[, dim])¶Finite difference operator of matrix or vector.
gradient(F[, h])¶Compute differences along vector
F, usinghas the spacing between points. The default spacing is one.
rot180(A)¶Rotate matrix
A180 degrees.
rot180(A, k)Rotate matrix
A180 degrees an integerknumber of times. Ifkis even, this is equivalent to acopy.
rotl90(A)¶Rotate matrix
Aleft 90 degrees.
rotl90(A, k)Rotate matrix
Aleft 90 degrees an integerknumber of times. Ifkis zero or a multiple of four, this is equivalent to acopy.
rotr90(A)¶Rotate matrix
Aright 90 degrees.
rotr90(A, k)Rotate matrix
Aright 90 degrees an integerknumber of times. Ifkis zero or a multiple of four, this is equivalent to acopy.
reducedim(f, A, dims[, initial])¶Reduce 2-argument function
falong dimensions ofA.dimsis a vector specifying the dimensions to reduce, andinitialis the initial value to use in the reductions. For+,*,maxandmintheinitialargument 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.
mapreducedim(f, op, A, dims[, initial])¶Evaluates to the same as
reducedim(op,map(f,A),dims,f(initial)), but is generally faster because the intermediate array is avoided.
mapslices(f, A, dims)¶Transform the given dimensions of array
Ausing functionf.fis called on each slice ofAof the formA[...,:,...,:,...].dimsis an integer vector specifying where the colons go in this expression. The results are concatenated along the remaining dimensions. For example, ifdimsis[1,2]andAis 4-dimensional,fis called onA[:,:,i,j]for alliandj.
sum_kbn(A)¶Returns the sum of all array elements, using the Kahan-Babuska-Neumaier compensated summation algorithm for additional accuracy.
Combinatorics¶
nthperm(v, k)¶Compute the kth lexicographic permutation of a vector.
nthperm(p)Return the
kthat generated permutationp. Note thatnthperm(nthperm([1:n],k))==kfor1<=k<=factorial(n).
randperm([rng, ]n)¶Construct a random permutation of length
n. The optionalrngargument specifies a random number generator, see Random Numbers.
invperm(v)¶Return the inverse permutation of v.
isperm(v) → Bool¶Returns
trueifvis a valid permutation.
permute!(v, p)¶Permute vector
vin-place, according to permutationp. No checking is done to verify thatpis 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([rng, ]n)¶Construct a random cyclic permutation of length
n. The optionalrngargument specifies a random number generator, see Random Numbers.
shuffle([rng, ]v)¶Return a randomly permuted copy of
v. The optionalrngargument specifies a random number generator, see Random Numbers.
reverse(v[, start=1[, stop=length(v)]])¶Return a copy of
vreversed from start to stop.
reverseind(v, i)¶Given an index
iinreverse(v), return the corresponding index invso thatv[reverseind(v,i)]==reverse(v)[i]. (This can be nontrivial in the case wherevis a Unicode string.)
combinations(array, n)¶Generate all combinations of
nelements from an indexable object. Because the number of combinations can be very large, this function returns an iterator object. Usecollect(combinations(array,n))to get an array of all combinations.
permutations(array)¶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(array))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 generate can be efficiently computed usinglength(partitions(n)).
partitions(n, m)Generate all arrays of
mintegers 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 generate 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 generate 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!(dest::BitArray{1}, src::BitArray{1}, i::Integer) → BitArray{1}¶Performs a left rotation operation on
srcand put the result intodest.
rol!(B::BitArray{1}, i::Integer) → BitArray{1}Performs a left rotation operation on
B.
rol(B::BitArray{1}, i::Integer) → BitArray{1}¶Performs a left rotation operation.
ror!(dest::BitArray{1}, src::BitArray{1}, i::Integer) → BitArray{1}¶Performs a right rotation operation on
srcand put the result intodest.
ror!(B::BitArray{1}, i::Integer) → BitArray{1}Performs a right rotation operation on
B.
ror(B::BitArray{1}, i::Integer) → BitArray{1}¶Performs a right rotation operation.
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
Sof dimensionsmxnsuch thatS[I[k],J[k]]=V[k]. Thecombinefunction is used to combine duplicates. Ifmandnare not specified, they are set tomaximum(I)andmaximum(J)respectively. If thecombinefunction is not supplied, duplicates are added by default. All elements ofImust satisfy1<=I[k]<=m, and all elements ofJmust satisfy1<=J[k]<=n.
sparsevec(I, V[, m, combine])¶Create a sparse matrix
Sof sizemx1such thatS[I[k]]=V[k]. Duplicates are combined using thecombinefunction, 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
mx1where the row values are keys from the dictionary, and the nonzero values are the values from the dictionary.
issparse(S)¶Returns
trueifSis sparse, andfalseotherwise.
sparse(A)Convert an AbstractMatrix
Ainto a sparse matrix.
sparsevec(A)Convert a dense vector
Ainto a sparse matrix of sizemx1. In julia, sparse vectors are really just sparse matrices with one column.
full(S)¶Convert a sparse matrix
Sinto a dense matrix.
nnz(A)¶Returns the number of stored (filled) elements in a sparse matrix.
spzeros(m, n)¶Create a sparse matrix of size
mxn. This sparse matrix will not contain any nonzero values. No storage will be allocated for nonzero values during construction.
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
mxm. In casenis supplied, create a sparse identity matrix of sizemxn.
spdiagm(B, d[, m, n])¶Construct a sparse diagonal matrix.
Bis a tuple of vectors containing the diagonals anddis a tuple containing the positions of the diagonals. In the case the input contains only one diagonal,Bcan be a vector (instead of a tuple) anddcan be the diagonal position (instead of a tuple), defaulting to 0 (diagonal). Optionally,mandnspecify the size of the resulting sparse matrix.
sprand([rng, ]m, n, p[, rfn])¶Create a random
mbynsparse 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 byrfn. The uniform distribution is used in caserfnis not specified. The optionalrngargument specifies a random number generator, see Random Numbers.
sprandn(m, n, p)¶Create a random
mbynsparse matrix with the specified (independent) probabilitypof any entry being nonzero, where nonzero values are sampled from the normal distribution.
sprandbool(m, n, p)¶Create a random
mbynsparse boolean matrix with the specified (independent) probabilitypof any entry beingtrue.
etree(A[, post])¶Compute the elimination tree of a symmetric sparse matrix
Afromtriu(A)and, optionally, its post-ordering permutation.
symperm(A, p)¶Return the symmetric permutation of
A, which isA[p,p].Ashould 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 mutateAas well. Seerowvals(A)andnzrange(A,col).
rowvals(A)¶Return a vector of the row indices of
A, and any modifications to the returned vector will mutateAas well. Given the internal storage format of sparse matrices, providing access to how the row indices are stored internally can be useful in conjunction with iterating over structural nonzero values. Seenonzeros(A)andnzrange(A,col).
nzrange(A, col)¶Return the range of indices to the structural nonzero values of a sparse matrix column. In conjunction with
nonzeros(A)androwvals(A), this allows for convenient iterating over a sparse matrix :A=sparse(I,J,V)rows=rowvals(A)vals=nonzeros(A)m,n=size(A)fori=1:nforjinnzrange(A,i)row=rows[j]val=vals[j]# perform sparse wizardry...endend