Engee documentation

Arrays

Constructors and types

AbstractArray{T,N}

A supertype for N-dimensional arrays (or array-like types) with elements of type T'. `Array and other types are subtypes of this type. See the interface section of the manual. AbstractArray.

See also the description AbstractVector, AbstractMatrix, eltype, ndims.

AbstractVector{T}

A supertype for one-dimensional arrays (or array-like types) with elements of type T'. An alias for `AbstractArray{T,1}.

AbstractMatrix{T}

A supertype for two-dimensional arrays (or array-like types) with elements of type T'. An alias for `AbstractArray{T,2}.

AbstractVecOrMat{T}

Type of association AbstractVector{T} and AbstractMatrix{T}.

Array{T,N} <: AbstractArray{T,N}

N is a dense three-dimensional array with elements of type T.

Array{T}(undef, dims)
Array{T,N}(undef, dims)

Creates an uninitialized N-dimensional array Array containing elements of type T'. `N can be provided explicitly, as in Array{T,N}(undef, dims), or be determined by the length or number of dims'. `dims can be a tuple or a series of integer arguments corresponding to the length in each dimension. If the rank of N is specified explicitly, it must match the length or number of dims'. Here `undef is a type UndefInitializer.

Examples

julia> A = Array{Float64, 2}(undef, 2, 3) # N задан явным образом
2×3 Matrix{Float64}:
 6.90198e-310  6.90198e-310  6.90198e-310
 6.90198e-310  6.90198e-310  0.0

julia> B = Array{Float64}(undef, 4) # N определен входными данными
4-element Vector{Float64}:
   2.360075077e-314
 NaN
   2.2671131793e-314
   2.299821756e-314

julia> similar(B, 2, 4, 1) # использовать typeof(B) и заданный размер
2×4×1 Array{Float64, 3}:
[:, :, 1] =
 2.26703e-314  2.26708e-314  0.0           2.80997e-314
 0.0           2.26703e-314  2.26708e-314  0.0
Array{T}(nothing, dims)
Array{T,N}(nothing, dims)

Creates an N-dimensional array Array containing elements of type T that are initialized with values nothing. The element type T must be able to store these values, i.e. Nothing <: T.

Examples

julia> Array{Union{Nothing, String}}(nothing, 2)
2-element Vector{Union{Nothing, String}}:
 nothing
 nothing

julia> Array{Union{Nothing, Int}}(nothing, 2, 3)
2×3 Matrix{Union{Nothing, Int64}}:
 nothing  nothing  nothing
 nothing  nothing  nothing
Array{T}(missing, dims)
Array{T,N}(missing, dims)

Creates an N-dimensional array Array containing elements of type T that are initialized with values missing. The element type T must be able to store these values, i.e. Missing <: T.

Examples

julia> Array{Union{Missing, String}}(missing, 2)
2-element Vector{Union{Missing, String}}:
 missing
 missing

julia> Array{Union{Missing, Int}}(missing, 2, 3)
2×3 Matrix{Union{Missing, Int64}}:
 missing  missing  missing
 missing  missing  missing
UndefInitializer

A single type used when initializing an array and indicating that the caller of the array constructor requires an uninitialized array. See also the description undef, an alias for `UndefInitializer()'.

Examples

julia> Array{Float64, 1}(UndefInitializer(), 3)
3-element Array{Float64, 1}:
 2.2752528595e-314
 2.202942107e-314
 2.275252907e-314
undef

An alias for UndefInitializer(), which creates an instance of a single type UndefInitializer, used during array initialization to indicate that the caller of the array constructor needs an uninitialized array.

See also the description missing, similar.

Examples

julia> Array{Float64, 1}(undef, 3)
3-element Vector{Float64}:
 2.2752528595e-314
 2.202942107e-314
 2.275252907e-314
Vector{T} <: AbstractVector{T}

A one-dimensional dense array with elements of type T, often used to represent a mathematical vector. An alias for Array{T,1}.

See also the function description empty, similar and zero to create vectors.

Vector{T}(undef, n)

Creates an uninitialized vector Vector{T} of length n.

Examples

julia> Vector{Float64}(undef, 3)
3-element Array{Float64, 1}:
 6.90966e-310
 6.90966e-310
 6.90966e-310
Vector{T}(nothing, m)

Creates a vector Vector{T} of length m, initialized with values nothing. The element type T must be able to store these values, i.e. Nothing <: T.

Examples

julia> Vector{Union{Nothing, String}}(nothing, 2)
2-element Vector{Union{Nothing, String}}:
 nothing
 nothing
Vector{T}(missing, m)

Creates a vector Vector{T} of length m, initialized with values missing. The element type T must be able to store these values, i.e. Missing <: T.

Examples

julia> Vector{Union{Missing, String}}(missing, 2)
2-element Vector{Union{Missing, String}}:
 missing
 missing
Matrix{T} <: AbstractMatrix{T}

A two-dimensional dense array with elements of type T, often used to represent a mathematical matrix. An alias for Array{T,2}.

See also the function description fill, zeros, undef and similar to create matrices.

Matrix{T}(undef, m, n)

Creates an uninitialized matrix Matrix{T} of the size m×n.

Examples

julia> Matrix{Float64}(undef, 2, 3)
2×3 Array{Float64, 2}:
 2.36365e-314  2.28473e-314    5.0e-324
 2.26704e-314  2.26711e-314  NaN

julia> similar(ans, Int32, 2, 2)
2×2 Matrix{Int32}:
 490537216  1277177453
         1  1936748399
Matrix{T}(nothing, m, n)

Creates a matrix Matrix{T} of the size m×n, initialized with the values nothing. The element type T must be able to store these values, i.e. Nothing <: T.

Examples

julia> Matrix{Union{Nothing, String}}(nothing, 2, 3)
2×3 Matrix{Union{Nothing, String}}:
 nothing  nothing  nothing
 nothing  nothing  nothing
Matrix{T}(missing, m, n)

Creates a matrix Matrix{T} of the size m×n, initialized with the values missing. The element type T must be able to store these values, i.e. Missing <: T.

Examples

julia> Matrix{Union{Missing, String}}(missing, 2, 3)
2×3 Matrix{Union{Missing, String}}:
 missing  missing  missing
 missing  missing  missing
VecOrMat{T}

Type of association Vector{T} and Matrix{T}, which allows functions to accept a matrix or vector.

Examples

julia> Vector{Float64} <: VecOrMat{Float64}
true

julia> Matrix{Float64} <: VecOrMat{Float64}
true

julia> Array{Float64, 3} <: VecOrMat{Float64}
false
DenseArray{T, N} <: AbstractArray{T,N}

N is a dense three-dimensional array with elements of type T. The elements of a dense array are stored in memory in a continuous sequence.

DenseVector{T}

One-dimensional array DenseArray with elements of type T'. An alias for `DenseArray{T,1}.

DenseMatrix{T}

Two-dimensional array DenseArray with elements of type T'. An alias for `DenseArray{T,2}.

DenseVecOrMat{T}

Type of association DenseVector{T} and DenseMatrix{T}.

StridedArray{T, N}

A hard-coded type Union common array types that follow array interface with steps, with elements of type T and N dimensions.

If A is a 'StridedArray', then its elements are stored in memory with offsets that may be different in different dimensions, but are constant within the same dimension. For example, A may have an array step of 2 in dimension 1 and an array step of 3 in dimension 2. When incrementing A in dimension d, memory is switched to [stride(A, d)] slots. Arrays with a given step are especially important and useful, because sometimes they can be passed directly as pointers to libraries in other languages, such as BLAS.

StridedVector{T}

One-dimensional array StridedArray with elements of type `T'.

StridedMatrix{T}

Two-dimensional array StridedArray with elements of type `T'.

StridedVecOrMat{T}

Type of association StridedVector and StridedMatrix with elements of type `T'.

GenericMemory{kind::Symbol, T, addrspace=Core.CPU} <: DenseVector{T}

Vector DenseVector{T} of a fixed size.

Currently, kind can have the value :not_atomic or :atomic. For more information about the value of :atomic, see the description AtomicMemory

Currently, only Core.CPU can be set for 'addrspace'. This argument suggests the possibility of expansion by other systems, such as GPUs, which can define, for example, the following values:

module CUDA
const Generic = bitcast(Core.AddrSpace{CUDA}, 0)
const Global = bitcast(Core.AddrSpace{CUDA}, 1)
end

The exact meaning of these additional address spaces is determined by the specific backend, but if the user tries to access them while running on the CPU, an error will occur.

Compatibility: Julia 1.11

This type requires a Julia version not lower than 1.11.

Memory{T} == GenericMemory{:not_atomic, T, Core.CPU}

Vector DenseVector{T} of a fixed size.

Compatibility: Julia 1.11

This type requires a Julia version not lower than 1.11.

`memoryref(::GenericMemory)`

Creates a GenericMemoryRef based on the memory object. An error will not occur, but the resulting reference will point to a memory area outside the allowed range only if the memory is empty.


memoryref(::GenericMemory, index::Integer)
memoryref(::GenericMemoryRef, index::Integer)

Creates a GenericMemoryRef based on the memory object and the offset index (starting from 1), which can also be negative. It always returns an object within the bounds and returns an error if this is not possible (since the index will lead to an offset outside the base memory).

Slices{P,SM,AX,S,N} <: AbstractSlices{S,N}

An array of AbstractArray slices of the parent array for a given change (dimensions), returning views that select all data from another dimension (dimensions).

They are usually built using eachslice, eachcol or eachrow.

parent(s::Slices) returns the parent array.

RowSlices{M,AX,S}

A special case Slices, which is a vector of slices of matrix rows constructed using eachrow.

parent can be used to get the base matrix.

ColumnSlices{M,AX,S}

A special case Slices', which is a vector of slices of matrix columns constructed using `eachcol.

parent can be used to get the base matrix.

getindex(type[, elements...])

Creates a one-dimensional array of the specified type. It is usually called using the syntax Type[]'. The values of the elements can be specified using `+Type[a,b,c,…​]+.

Examples

julia> Int8[1, 2, 3]
3-element Vector{Int8}:
 1
 2
 3

julia> getindex(Int8, 1, 2, 3)
3-element Vector{Int8}:
 1
 2
 3
zeros([T=Float64,] dims::Tuple)
zeros([T=Float64,] dims...)

Creates an array Array with the element type T, containing only zeros and having the size dims'. See also the description `fill, ones and zero.

Examples

julia> zeros(1)
1-element Vector{Float64}:
 0.0

julia> zeros(Int8, 2, 3)
2×3 Matrix{Int8}:
 0  0  0
 0  0  0
ones([T=Float64,] dims::Tuple)
ones([T=Float64,] dims...)

Creates an array Array with the element type T, containing one unit and having the size dims'. See also the description `fill and zeros.

Examples

julia> ones(1,2)
1×2 Matrix{Float64}:
 1.0  1.0

julia> ones(ComplexF64, 2, 3)
2×3 Matrix{ComplexF64}:
 1.0+0.0im  1.0+0.0im  1.0+0.0im
 1.0+0.0im  1.0+0.0im  1.0+0.0im
BitArray{N} <: AbstractArray{Bool, N}

A compact N-dimensional logical array using only one bit for each logical value.

'BitArray` packs up to 64 values into every 8 bytes, which results in 8x space efficiency compared to Array{Bool, N} and allows some operations to work with 64 values simultaneously.

By default, Julia returns BitArrays from operations translations that create logical elements (including comparisons with dotted lines, similar to .==), as well as from functions trues' and `falses.

Due to the packaged storage format, simultaneous access operations to BitArray elements, at least one of which is a write operation, are not thread-safe.

BitArray(undef, dims::Integer...)
BitArray{N}(undef, dims::NTuple{N,Int})

Creates an undefined array BitArray with the specified dimensions. It works similarly to the constructor Array. See description undef.

Examples

julia> BitArray(undef, 2, 2)
2×2 BitMatrix:
 0  0
 0  0

julia> BitArray(undef, (3, 1))
3×1 BitMatrix:
 0
 0
 0
BitArray(itr)

Creates an array BitArray generated by the specified iterable object. The form is derived from the 'itr` object.

Examples

julia> BitArray([1 0; 0 1])
2×2 BitMatrix:
 1  0
 0  1

julia> BitArray(x+y == 3 for x = 1:2, y = 1:3)
2×3 BitMatrix:
 0  1  0
 1  0  0

julia> BitArray(x+y == 3 for x = 1:2 for y = 1:3)
6-element BitVector:
 0
 1
 0
 1
 0
 0
trues(dims)

Creates a `BitArray' array with all values set to `true'.

Examples

julia> trues(2,3)
2×3 BitMatrix:
 1  1  1
 1  1  1
falses(dims)

Creates a `BitArray' array with all values set to `false'.

Examples

julia> falses(2,3)
2×3 BitMatrix:
 0  0  0
 0  0  0
fill(value, dims::Tuple)
fill(value, dims...)

Creates an array of the size of dims, in which each position is assigned a value of value.

For example, fill(1.0, (5.5)) returns a 5×5 array of floating-point numbers with the value 1.0 at each position.

The length of the dims' dimension can be set as a tuple or a sequence of arguments. A tuple of length `N or N arguments after value sets an 'N`-dimensional array. Thus, a common method for creating a zero-dimensional array with a single location specified as x is `fill(x)'.

Each position of the returned array is assigned the passed value value, which the position will be identical to (===). This means that when you change the value itself, this change will be reflected in all the elements of the array to which the fill function is applied, because they are still the same value'. This has nothing to do with `fill(1.0, (5.5)), because the value of value 1.0 is immutable and cannot be changed by itself. However, when using mutable values, such as (most often) arrays, the result may be unexpected. For example, calling fill([], 3) places the same empty array in all three positions of the returned vector.:

julia> v = fill([], 3)
3-element Vector{Vector{Any}}:
 []
 []
 []

julia> v[1] === v[2] === v[3]
true

julia> value = v[1]
Any[]

julia> push!(value, 867_5309)
1-element Vector{Any}:
 8675309

julia> v
3-element Vector{Vector{Any}}:
 [8675309]
 [8675309]
 [8675309]

To create an array of multiple independent internal arrays, use enabling. In this case, a new and separate array is created at each iteration of the loop.:

julia> v2 = [[] for _ in 1:3]
3-element Vector{Vector{Any}}:
 []
 []
 []

julia> v2[1] === v2[2] === v2[3]
false

julia> push!(v2[1], 8675309)
1-element Vector{Any}:
 8675309

julia> v2
3-element Vector{Vector{Any}}:
 [8675309]
 []
 []

See also the description fill!, zeros, ones, similar.

Examples

julia> fill(1.0, (2,3))
2×3 Matrix{Float64}:
 1.0  1.0  1.0
 1.0  1.0  1.0

julia> fill(42)
0-dimensional Array{Int64, 0}:
42

julia> A = fill(zeros(2), 2) # задает для обоих элементов один и тот же вектор [0.0, 0.0]
2-element Vector{Vector{Float64}}:
 [0.0, 0.0]
 [0.0, 0.0]

julia> A[1][1] = 42; # изменяет заполненное значение на [42.0, 0.0]

julia> A # A[1] и A[2] являются одним и тем же вектором
2-element Vector{Vector{Float64}}:
 [42.0, 0.0]
 [42.0, 0.0]
fill!(A, x)

Fills the array A with the value x. If 'x` is a reference to an object, all objects will refer to the same object. fill!(A, Foo()) returns an array A filled with the result of a single calculation of `Foo()'.

Examples

julia> A = zeros(2,3)
2×3 Matrix{Float64}:
 0.0  0.0  0.0
 0.0  0.0  0.0

julia> fill!(A, 2.)
2×3 Matrix{Float64}:
 2.0  2.0  2.0
 2.0  2.0  2.0

julia> a = [1, 1, 1]; A = fill!(Vector{Vector{Int}}(undef, 3), a); a[1] = 2; A
3-element Vector{Vector{Int64}}:
 [2, 1, 1]
 [2, 1, 1]
 [2, 1, 1]

julia> x = 0; f() = (global x += 1; x); fill!(Vector{Int}(undef, 3), f())
3-element Vector{Int64}:
 1
 1
 1
empty(x::Tuple)

Returns an empty tuple ().


empty(v::AbstractVector, [eltype])

Creates an empty vector similar to v', changing the `eltype if necessary.

See also the description empty!, isempty, isassigned.

Examples

julia> empty([1.0, 2.0, 3.0])
Float64[]

julia> empty([1.0, 2.0, 3.0], String)
String[]

empty(a::AbstractDict, [index_type=keytype(a)], [value_type=valtype(a)])

Creates an empty container AbstractDict, which can accept indexes of type index_type and values of type value_type'. The second and third arguments are optional and by default have the values `keytype and valtype of the input data, respectively. (If only one of the two types is specified, it is assumed that it is value_type, and for index_type, keytype(a) will be used by default.)

Custom subtypes of AbstractDict' can choose which specific dictionary type is best suited for returning specified index and value types by specializing the three-argument signature. By default, an empty `Dict is returned.

similar(A::AbstractSparseMatrixCSC{Tv,Ti}, [::Type{TvNew}, ::Type{TiNew}, m::Integer, n::Integer]) where {Tv,Ti}

Creates an uninitialized mutable array with the specified element type, index type, and size based on the specified source object `SparseMatrixCSC'. The new sparse matrix retains the structure of the original sparse matrix, except when the measurements of the output matrix differ from the output data.

The output matrix has zeros in the same locations as the input matrix, but has uninitialized values in non-zero locations.


similar(array, [element_type=eltype(array)], [dims=size(array)])

Creates an uninitialized mutable array with the specified element type and size based on the specified source array. The second and third arguments are optional and have the default values of eltype and size of the specified array. Dimensions can be specified either as a single tuple argument or as a series of integer arguments.

Custom AbstractArray subtypes can choose which specific dictionary type is best suited for returning a given element type and dimension. If they don’t specialize this method, Array' is used by default.{element_type}(undef, dims...).

For example, similar(1:10, 1, 4) returns an uninitialized array `Array{Int,2}because the ranges are not changeable and do not support two dimensions:

julia> similar(1:10, 1, 4)
1×4 Matrix{Int64}:
 4419743872  4374413872  4419743888  0

Conversely, similar(trues(10,10), 2) returns an uninitialized BitVector vector with two elements, since BitArray is mutable and can support one-dimensional arrays.:

julia> similar(trues(10,10), 2)
2-element BitVector:
 0
 0

Because BitArray can only store elements of the type Bool, if you request a different type of elements, a regular Array will be created:

julia> similar(falses(10), Float64, 2, 4)
2×4 Matrix{Float64}:
 2.18425e-314  2.18425e-314  2.18425e-314  2.18425e-314
 2.18425e-314  2.18425e-314  2.18425e-314  2.18425e-314

See also the description undef, isassigned.


similar(storagetype, axes)

Creates an uninitialized mutable array, similar to the one specified using storagetype, but with `axes' set as the last argument.

Examples:

similar(Array{Int}, axes(A))

creates an array that acts as a Array{Int} (and indeed can be based on it), but indexed identically to A'. If `A has regular indexing, it will be identical to Array{Int}(undef, size(A)), but if A has non-traditional indexing, then the result indexes will match A.

similar(BitArray, (axes(A, 2),))

creates a one-dimensional logical array whose indexes match the indexes of the columns `A'.

Main functions

ndims(A::AbstractArray) -> Integer

Returns the number of dimensions of `A'.

See also the description size, axes.

Examples

julia> A = fill(1, (3,4,5));

julia> ndims(A)
3
size(A::AbstractArray, [dim])

Returns a tuple containing the dimensions `A'. If necessary, you can specify a dimension to get the length of that dimension only.

Note that the size function may not be defined for arrays with non-standard indexes. In this case, the method may be useful. axes. See the manual chapter on arrays with custom indexes.

See also the description length, ndims, eachindex, sizeof.

Examples

julia> A = fill(1, (2,3,4));

julia> size(A)
(2, 3, 4)

julia> size(A, 2)
3
axes(A)

Returns a tuple of valid indexes for the array `A'.

See also the description size, keys, eachindex.

Examples

julia> A = fill(1, (5,6,7));

julia> axes(A)
(Base.OneTo(5), Base.OneTo(6), Base.OneTo(7))
axes(A, d)

Returns the allowed range of indexes for array A in dimension `d'.

See also the function description size and the manual chapter about arrays with custom indexes.

Examples

julia> A = fill(1, (5,6,7));

julia> axes(A, 2)
Base.OneTo(6)

julia> axes(A, 4) == 1:1  # все измерения d > ndims(A) имеют размер, равный 1
true

Note on usage

Each of the indexes should be an AbstractUnitRange{<:Integer}, but at the same time it can have a type that uses custom indexes. So, for example, if you need a subset, use generalized indexing constructs such as begin/end' or `firstindex/lastindex:

ix = axes(v, 1)
ix[2:end]          # будет работать для, например, вектора, но может завершиться сбоем в общем случае
ix[(begin+1):end]  # работает для обобщенных индексов
length(A::AbstractArray)

Returns the number of elements in the array; by default, prod(size(A))' is used.

Examples

julia> length([1, 2, 3, 4])
4

julia> length([1 2; 3 4])
4
keys(a::AbstractArray)

Returns a productive array describing all valid indexes for a in the form of a itself.

The keys of one-dimensional arrays (vectors) are integers, whereas all other N-dimensional arrays use CartesianIndex' to describe your positions. Often special types of arrays `LinearIndices and `CartesianIndices' are used to efficiently represent these arrays of integers and `CartesianIndex' respectively.

Note that the keys of an array may not be the most efficient type of index. To achieve maximum performance, use eachindex.

Examples

julia> keys([4, 5, 6])
3-element LinearIndices{1, Tuple{Base.OneTo{Int64}}}:
 1
 2
 3

julia> keys([4 5; 6 7])
CartesianIndices((2, 2))
eachindex(A...)
eachindex(::IndexStyle, A::AbstractArray...)

Creates an iterable object for efficient traversal of each index of AbstractArray A'. For array types with fast linear indexing (such as `Array'), this is simply the range `1:length(A) if they use indexing from one. For array types without fast linear indexing, a specialized Cartesian range is usually returned for efficient array indexing with indexes specified for each dimension.

In general, eachindex accepts arbitrary iterable objects, including strings and dictionaries, and returns an iterator object that supports arbitrary types of indexes (for example, unevenly distributed or non-integer indexes).

If A is an AbstractArray, you can explicitly specify the style of the indexes to be returned by the eachindex function by passing an IndexStyle type value as the first argument (usually IndexLinear() if linear indexes are required, or IndexCartesian() if a Cartesian range is required).

If you have specified multiple arguments to AbstractArray, eachindex' will create an iterable object that is fast for all arguments (usually 'UnitRange, if all input data has fast linear indexing, or CartesianIndices' otherwise). If the arrays have different sizes and/or dimensions, a `DimensionMismatch exception will occur.

See also the description pairs(A) for combined index and value iteration and description axes(A, 2) for valid indexes in one dimension.

Examples

julia> A = [10 20; 30 40];

julia> for i in eachindex(A) # линейное индексирование
           println("A[", i, "] == ", A[i])
       end
A[1] == 10
A[2] == 30
A[3] == 20
A[4] == 40

julia> for i in eachindex(view(A, 1:2, 1:1)) # декартово индексирование
           println(i)
       end
CartesianIndex(1, 1)
CartesianIndex(2, 1)
IndexStyle(A)
IndexStyle(typeof(A))

IndexStyle sets a custom indexing style for the array A'. When defining a new type `AbstractArray can be implemented either as linear indexing (using IndexLinear), or Cartesian indexing. If you decide to implement only linear indexing, you must specify this point for the array type.:

Base.IndexStyle(::Type{<:MyArray}) = IndexLinear()

By default, it is used IndexCartesian().

Julia’s internal indexing engine will automatically (and imperceptibly) recalculate all indexing operations to your preferred style. This allows users to access the elements of your array using any indexing style, even if explicit methods have not been provided.

If you have defined both indexing styles for your AbstractArray, you can use this feature to select the most efficient indexing style. Some methods check this feature in their input data and perform dispatching into various algorithms depending on the most efficient access scheme. In particular, 'eachindex' creates an iterator, the type of which depends on the indication of this attribute.

IndexLinear()

Subtype `IndexStyle', used to describe arrays that are optimally indexed by a single linear index.

The linear indexing style uses a single integer index to describe the position in an array (even if it is a multidimensional array), and column ordering is used to efficiently access the elements. This means that when requesting 'eachindex` a simple one-dimensional range will be returned from an array that is IndexLinear, even if it is multidimensional.

A custom array that reports its IndexStyle as IndexLinear must implement indexing (and indexed assignment) with only one Int index. All other indexing expressions, including multidimensional access, will be converted to a linear index. For example, if the array A were a user-defined 2×3' matrix with linear indexing and we accessed the index `A[1, 3], it would be recalculated into an equivalent linear index with the call A[5], since 1 + 2*(3 - 1) = 5.

See also the description IndexCartesian.

IndexCartesian()

Subtype IndexStyle', used to describe arrays that are optimally indexed by a single Cartesian index. Used by default for new custom subtypes. `AbstractArray.

The Cartesian indexing style uses multiple integer indexes to describe a position in a multidimensional array with exactly one index per dimension. This means that when requesting eachindex a range will be returned from an array that is IndexCartesian CartesianIndices.

A custom N-dimensional array that reports its IndexStyle as IndexCartesian' must implement indexing (and indexed assignment) with exactly `N indexes of Int. All other indexing expressions, including linear indexing, will be recalculated to the equivalent Cartesian layout. For example, if the array A were a custom 2×3 matrix with Cartesian indexing and we accessed the index A[5], it would be recalculated into an equivalent Cartesian index with the call A[1, 3], since 5 = 1 + 2*(3 - 1).

Calculating Cartesian indexes from a linear index is much more expensive. The first operation requires division (a very expensive operation), whereas the second uses only multiplication and addition, so it is essentially free. This asymmetry means that using linear indexing using the IndexCartesian array is much more expensive than using Cartesian indexing using the IndexLinear array.

See also the description IndexLinear.

conj!(A)

Converts an array to its complex conjugate value in place.

See also the description conj.

Examples

julia> A = [1+im 2-im; 2+2im 3+im]
2×2 Matrix{Complex{Int64}}:
 1+1im  2-1im
 2+2im  3+1im

julia> conj!(A);

julia> A
2×2 Matrix{Complex{Int64}}:
 1-1im  2+1im
 2-2im  3-1im
stride(A, k::Integer)

Returns the distance in memory (in the form of the number of elements) between adjacent elements in dimension `k'.

See also the description strides.

Examples

julia> A = fill(1, (3,4,5));

julia> stride(A,2)
3

julia> stride(A,3)
12
strides(A)

Returns a tuple of memory steps in each dimension.

See also the description stride.

Examples

julia> A = fill(1, (3,4,5));

julia> strides(A)
(1, 3, 12)

Translation and vectorization

See also the section Dot-separated syntax for vectorization functions. For example, f.(args...) implicitly calls broadcast(f, args...). Instead of relying on "vectorized" function methods, such as sin, to work with arrays, you should use sin.(a) for vectorization by means of `broadcast'.

broadcast(f, As...)

Translates the function f in arrays, tuples, collections, types Ref and (or) scalars `As'.

The translation applies the function f to the elements of the container arguments and the scalars themselves in As. Single and missing dimensions are expanded according to the sizes of the other arguments, practically repeating the value. By default, only a limited number of types are considered scalar, including Number, String, Symbol, Type, Function and some other common single types such as missing and nothing. All other arguments are iterated or indexed element by element.

The resulting container type is determined by the rules below.

  • If all arguments are scalars or zero-dimensional arrays, a scalar without a shell is returned.

  • If at least one argument is a tuple, and all the others are scalars or zero-dimensional arrays, it returns a tuple.

  • All other argument combinations return Array by default, but custom container types can define their own implementation and promotion rules to customize the result when they are used as arguments.

There is a special syntax for translation: f.(args...) is equivalent to broadcast(f, args...), and nested calls f.(g.(args...)) are combined into one broadcast cycle.

Examples

julia> A = [1, 2, 3, 4, 5]
5-element Vector{Int64}:
 1
 2
 3
 4
 5

julia> B = [1 2; 3 4; 5 6; 7 8; 9 10]
5×2 Matrix{Int64}:
 1   2
 3   4
 5   6
 7   8
 9  10

julia> broadcast(+, A, B)
5×2 Matrix{Int64}:
  2   3
  5   6
  8   9
 11  12
 14  15

julia> parse.(Int, ["1", "2"])
2-element Vector{Int64}:
 1
 2

julia> abs.((1, -2))
(1, 2)

julia> broadcast(+, 1.0, (0, -2.0))
(1.0, -1.0)

julia> (+).([[0,2], [1,3]], Ref{Vector{Int}}([1,-1]))
2-element Vector{Vector{Int64}}:
 [1, 1]
 [2, 2]

julia> string.(("one","two","three","four"), ": ", 1:4)
4-element Vector{String}:
 "one: 1"
 "two: 2"
 "three: 3"
 "four: 4"
broadcast!(f, dest, As...)

Similarly broadcast, but stores the result broadcast(f, As...) in the 'dest` array. Note that the dest array is used only to store the result and does not provide arguments for f unless specified in As, for example broadcast!(f, A, A, B), to execute A[:] = broadcast(f, A, B).

Examples

julia> A = [1.0; 0.0]; B = [0.0; 0.0];

julia> broadcast!(+, B, A, (0, -2.0));

julia> B
2-element Vector{Float64}:
  1.0
 -2.0

julia> A
2-element Vector{Float64}:
 1.0
 0.0

julia> broadcast!(+, A, A, (0, -2.0));

julia> A
2-element Vector{Float64}:
  1.0
 -2.0
@. expr

Converts every function call or statement in expr to a 'dot call' (for example, converts f(x) to f.(x)) and converts every assignment in expr to a 'dot assignment' (for example, converts += to .+=).

To not add these points for selected function calls to expr, use $ in the calls. For example, calling @. sqrt(abs($sort(x))) is equivalent to sqrt.(abs.(sort(x))) (there is no dot for sort).

('@.` is equivalent to calling `@__dot__'.)

Examples

julia> x = 1.0:3.0; y = similar(x);

julia> @. y = x + 3 * sin(x)
3-element Vector{Float64}:
 3.5244129544236893
 4.727892280477045
 3.4233600241796016

For information about specialized translation for user-defined types, see the description of the following type:

'BroadcastStyle' is an abstract type and a trace function used to determine the behavior of objects during broadcasting. BroadcastStyle(typeof(x)) returns the style associated with `x'. To customize the type behavior during translation, you can declare a style by defining a type/method pair.

struct MyContainerStyle <: BroadcastStyle end
Base.BroadcastStyle(::Type{<:MyContainer}) = MyContainerStyle()

Then the methods are created (at least similar) that work in Broadcast{MyContainerStyle}. There are several predefined subtypes of `BroadcastStyle' available for use. For more information, see to the "Interfaces" chapter.

Broadcast.AbstractArrayStyle{N} <: BroadcastStyle is an abstract supertype for any style associated with the AbstractArray type. The N parameter represents a dimension, which can be convenient for working with AbstractArray types that support only specific dimensions.:

struct SparseMatrixStyle <: Broadcast.AbstractArrayStyle{2} end
Base.BroadcastStyle(::Type{<:SparseMatrixCSC}) = SparseMatrixStyle()

For the AbstractArray' types that support an arbitrary dimension, the `N parameter can be set to Any:

struct MyArrayStyle <: Broadcast.AbstractArrayStyle{Any} end Base.BroadcastStyle(::Type{<:MyArray}) = MyArrayStyle()

In cases where you want to be able to mix multiple abstractarraystyles and control the dimensionality, your style must be supported by the constructor. Val:

struct MyArrayStyleDim{N} <: Broadcast.AbstractArrayStyle{N} end (::Type{<:MyArrayStyleDim})(::Val{N}) where N = MyArrayStyleDim{N}()

Note that if two or more subtypes of AbstractArrayStyle conflict, the translation engine will revert to creating an Array. If this is undesirable, you may need to define binary rules. BroadcastStyle to control the output type.

See also the description Broadcast.DefaultArrayStyle.

Broadcast.ArrayStyle{MyArrayType}() is a type BroadcastStyle, indicating that the object acts as an array for broadcasting. It is a simple way to build Broadcast.AbstractArrayStyle for specific container types AbstractArray'. The translation styles created in this way lose control over the dimension. If maintaining control is important for your type, you should create a custom type. `Broadcast.AbstractArrayStyle.

Broadcast.DefaultArrayStyle{N}() is a type BroadcastStyle', indicating that the object acts as an 'N-dimensional array for broadcasting. In particular, DefaultArrayStyle is used for any type of AbstractArray that lacks a specialized style, and in the absence of overrides from other broadcast arguments, the resulting output type is Array'. If there are multiple inputs for `broadcast, DefaultArrayStyle' is inferior to any other `Broadcast.ArrayStyle.

Broadcast.broadcastable(x)

Returns either x or an object of type x that supports axes, indexing, and its type supports ndims.

If 'x` supports iteration, the return value must have the same axes method and indexing behavior as collect(x).

If x is not an AbstractArray, but supports axes', indexing, and its type supports `ndims, the function 'broadcastable(::typeof(x))it can be implemented so that it simply returns the object itself. Further, if `x has its own defined BroadcastStyle, the broadcastable method must also be defined to return itself in order for the custom style to have any effect.

Examples

julia> Broadcast.broadcastable([1,2,3]) # аналогично идентификатору, поскольку массивы уже поддерживают оси и индексирование
3-element Vector{Int64}:
 1
 2
 3

julia> Broadcast.broadcastable(Int) # Типы не поддерживают оси, индексирование или итерацию, но обычно используются как скаляры
Base.RefValue{Type{Int64}}(Int64)

julia> Broadcast.broadcastable("hello") # Строки нарушают конвенцию итерации соответствия и действуют как скаляры
Base.RefValue{String}("hello")
combine_axes(As...) -> Tuple

Defines the result axes for translation across all values in `As'.

julia> Broadcast.combine_axes([1], [1 2; 3 4; 5 6])
(Base.OneTo(3), Base.OneTo(2))

julia> Broadcast.combine_axes(1, 1, 1)
()
combine_styles(cs...) -> BroadcastStyle

Decides which type of BroadcastStyle' to use for any number of value arguments. Uses `BroadcastStyle to get the style for each argument and function result_style for combining styles.

Examples

julia> Broadcast.combine_styles([1], [1 2; 3 4])
Base.Broadcast.DefaultArrayStyle{2}()
result_style(s1::BroadcastStyle[, s2::BroadcastStyle]) -> BroadcastStyle

Takes one or two broadcaststyles and combines them using BroadcastStyle to define a common `BroadcastStyle'.

Examples

julia> Broadcast.result_style(Broadcast.DefaultArrayStyle{0}(), Broadcast.DefaultArrayStyle{3}())
Base.Broadcast.DefaultArrayStyle{3}()

julia> Broadcast.result_style(Broadcast.Unknown(), Broadcast.DefaultArrayStyle{1}())
Base.Broadcast.DefaultArrayStyle{1}()

Indexing and assignment

getindex(A, inds...)

Returns a subset of the array A, selected using the indexes `inds'.

Each index can have any supported type, for example Integer, CartesianIndex, AbstractRange or array of supported indexes. To select all the elements in a particular dimension, you can use :, and to filter elements where the corresponding index is true, you can use a logical array (for example, Array{Bool} or BitArray).

If inds selects multiple elements, this function returns a new allocated array. To index multiple items without creating a copy, use view.

For more information, see the section of the manual on indexing arrays.

Examples

julia> A = [1 2; 3 4]
2×2 Matrix{Int64}:
 1  2
 3  4

julia> getindex(A, 1)
1

julia> getindex(A, [2, 1])
2-element Vector{Int64}:
 3
 1

julia> getindex(A, 2:4)
3-element Vector{Int64}:
 3
 2
 4

julia> getindex(A, 2, 1)
3

julia> getindex(A, CartesianIndex(2, 1))
3

julia> getindex(A, :, 2)
2-element Vector{Int64}:
 2
 4

julia> getindex(A, 2, :)
2-element Vector{Int64}:
 3
 4

julia> getindex(A, A .> 2)
2-element Vector{Int64}:
 3
 4
setindex!(A, X, inds...)
A[inds...] = X

Stores values from the array X within a subset of A specified using inds'. The syntax `+A[inds…​] = X+ is equivalent to (setindex!(A, X, inds...); X).

If any modified argument is placed in the same memory area as any other argument, the behavior may be unexpected.

Examples

julia> A = zeros(2,2);

julia> setindex!(A, [10, 20], [1, 2]);

julia> A[[3, 4]] = [30, 40];

julia> A
2×2 Matrix{Float64}:
 10.0  30.0
 20.0  40.0
nextind(A, i)

Returns the index after i in A. The returned index is often equivalent to i + 1 for the integer `i'. This feature can be useful for universal code.

The returned index may be outside the acceptable range. It is recommended to use checkbounds.

See also the description prevind.

Examples

julia> x = [1 2; 3 4]
2×2 Matrix{Int64}:
 1  2
 3  4

julia> nextind(x, 1) # допустимый результат
2

julia> nextind(x, 4) # недопустимый результат
5

julia> nextind(x, CartesianIndex(1, 1)) # допустимый результат
CartesianIndex(2, 1)

julia> nextind(x, CartesianIndex(2, 2)) # недопустимый результат
CartesianIndex(1, 3)
prevind(A, i)

Returns the index before i in A. The returned index is often equivalent to i - 1 for the integer `i'. This feature can be useful for universal code.

The returned index may be outside the acceptable range. It is recommended to use checkbounds.

See also the description nextind.

Examples

julia> x = [1 2; 3 4]
2×2 Matrix{Int64}:
 1  2
 3  4

julia> prevind(x, 4) # допустимый результат
3

julia> prevind(x, 1) # недопустимый результат
0

julia> prevind(x, CartesianIndex(2, 2)) # допустимый результат
CartesianIndex(1, 2)

julia> prevind(x, CartesianIndex(1, 1)) # недопустимый результат
CartesianIndex(2, 0)
copyto!(dest, Rdest::CartesianIndices, src, Rsrc::CartesianIndices) -> dest

Copies the src block in the Rsrc range to the dest block in the Rdest range. The sizes of the two regions must match.

Examples

julia> A = zeros(5, 5);

julia> B = [1 2; 3 4];

julia> Ainds = CartesianIndices((2:3, 2:3));

julia> Binds = CartesianIndices(B);

julia> copyto!(A, Ainds, B, Binds)
5×5 Matrix{Float64}:
 0.0  0.0  0.0  0.0  0.0
 0.0  1.0  2.0  0.0  0.0
 0.0  3.0  4.0  0.0  0.0
 0.0  0.0  0.0  0.0  0.0
 0.0  0.0  0.0  0.0  0.0
copy!(dst, src) -> dst

Copies src in place to dst using copy with the deletion of all existing elements in dst'. If `dst and src have the same type, 'dst == src` should be saved after the call. If 'dst` and src are multidimensional arrays, they must be equal axes.

If any modified argument is placed in the same memory area as any other argument, the behavior may be unexpected.

See also the description copyto!.

Compatibility: Julia 1.1

This method requires a Julia version at least 1.1. In Julia 1.0, this method is available in the standard library Future like Future.copy!.

isassigned(array, i) -> Bool

Checks whether there is a value associated with the index i in the specified array. Returns `false' if the index is out of bounds or has an undefined reference.

Examples

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 Vector{Foo}:
 #undef
 #undef
 #undef

julia> isassigned(v, 1)
false
Colon()

The colon (:) is used to indicate indexing of entire objects or dimensions.

Very few operations are defined directly for colons. But the function to_indices converts them to an internal vector type (Base.Slice) to represent the collection of indexes they cover before use.

A single instance of Colon' is also a function used to build ranges. See the description :`.

CartesianIndex(i, j, k...)   -> I
CartesianIndex((i, j, k...)) -> I

Creates a multidimensional index I', which can be used to index a multidimensional array `A'. In particular, `A[I] is equivalent to A[i,j,k...]. You can easily mix integer indexes and CartesianIndex indexes. For example, A[Ipre, i, Ipost] (where Ipre and Ipost are indexes of CartesianIndex' and `i is Int) can be a useful expression when writing algorithms that work in a single dimension of an array of arbitrary dimension.

A CartesianIndex is sometimes created using the function eachindex and always when iterating with an explicit CartesianIndices.

I::CartesianIndex is treated as a "scalar" (not a container) for broadcast'. To iterate through the components of the `CartesianIndex, convert it to a tuple using `Tuple(I)'.

Examples

julia> A = reshape(Vector(1:16), (2, 2, 2, 2))
2×2×2×2 Array{Int64, 4}:
[:, :, 1, 1] =
 1  3
 2  4

[:, :, 2, 1] =
 5  7
 6  8

[:, :, 1, 2] =
  9  11
 10  12

[:, :, 2, 2] =
 13  15
 14  16

julia> A[CartesianIndex((1, 1, 1, 1))]
1

julia> A[CartesianIndex((1, 1, 1, 2))]
9

julia> A[CartesianIndex((1, 1, 2, 1))]
5
Compatibility: Julia 1.10

To use CartesianIndex as a "scalar" for broadcast requires Julia 1.10; in previous versions, use Ref(I).

CartesianIndices(sz::Dims) -> R
CartesianIndices((istart:[istep:]istop, jstart:[jstep:]jstop, ...)) -> R

Defines the area R covering a multidimensional rectangular range of integer indexes. They are most often found in the context of iteration, where for I in R ... end returns indexes. CartesianIndex' `I, equivalent to nested loops.

for j = jstart:jstep:jstop for i = istart:istep:istop ... end end

Therefore, they can be useful for writing algorithms that work in arbitrary dimensions.

CartesianIndices(A::AbstractArray) -> R

For convenience, when creating `CartesianIndices', a range of its indexes is formed from the array.

Compatibility: Julia 1.6

For the step range method CartesianIndices((istart:istep:istop, jstart:[jstep:]jstop, ...)) requires a Julia version of at least 1.6.

Examples

julia> foreach(println, CartesianIndices((2, 2, 2)))
CartesianIndex(1, 1, 1)
CartesianIndex(2, 1, 1)
CartesianIndex(1, 2, 1)
CartesianIndex(2, 2, 1)
CartesianIndex(1, 1, 2)
CartesianIndex(2, 1, 2)
CartesianIndex(1, 2, 2)
CartesianIndex(2, 2, 2)

julia> CartesianIndices(fill(1, (2,3)))
CartesianIndices((2, 3))

Conversion of linear indexes to Cartesian ones

When converting a linear index to Cartesian, the fact that CartesianIndices is an AbstractArray and can be indexed linearly is used.:

julia> cartesian = CartesianIndices((1:3, 1:2))
CartesianIndices((1:3, 1:2))

julia> cartesian[4]
CartesianIndex(1, 2)

julia> cartesian = CartesianIndices((1:2:5, 1:2))
CartesianIndices((1:2:5, 1:2))

julia> cartesian[2, 2]
CartesianIndex(3, 2)

Broadcast

CartesianIndices' support arithmetic translation (+ and --) using `CartesianIndex.

Compatibility: Julia 1.1

The CartesianIndices broadcast requires a Julia version of at least 1.1.

julia> CIs = CartesianIndices((2:3, 5:6))
CartesianIndices((2:3, 5:6))

julia> CI = CartesianIndex(3, 4)
CartesianIndex(3, 4)

julia> CIs .+ CI
CartesianIndices((5:6, 9:10))

For information about converting Cartesian indexes to linear indexes, see the description LinearIndices.

Dims{N}

NTuple Of the N elements, the Int type is used to represent dimensions AbstractArray.

LinearIndices(A::AbstractArray)

Returns an array of LinearIndices with the same shape and axes, as for A, where the linear index of each record is in `A'. Indexing this array using Cartesian indexes allows you to map them to linear indexes.

For arrays with regular indexing (indexes start with 1) or any multidimensional arrays, linear indexes range from 1 to length(A)'. However, for the `AbstractVector, the linear indexes are axes(A, 1) and therefore do not start with 1 for vectors with non-traditional indexing.

Calling this function is a safe way to write algorithms that use linear indexing.

Examples

julia> A = fill(1, (5,6,7));

julia> b = LinearIndices(A);

julia> extrema(b)
(1, 210)
LinearIndices(inds::CartesianIndices) -> R LinearIndices(sz::Dims) -> R LinearIndices((istart:istop, jstart:jstop, ...)) -> R

Returns an array of LinearIndices' with the specified shape or `axes.

Examples

The main purpose of this constructor is the intuitive transformation of Cartesian indexing into linear indexing.:

julia> linear = LinearIndices((1:3, 1:2))
3×2 LinearIndices{2, Tuple{UnitRange{Int64}, UnitRange{Int64}}}:
 1  4
 2  5
 3  6

julia> linear[1,2]
4
to_indices(A, I::Tuple)

Converts the tuple I into a tuple of indexes for use when accessing the array A by indexes.

The returned tuple must contain only the Int or AbstractArray' scalar indexes supported by the array `A. If a new type of index is detected, the processing method of which is unknown, an error will occur.

When working with simple index types, a switch is made to the non-exported Base.to_index(A, i) to process each index i'. Although this internal function is not intended to be called directly, `Base.to_index can be extended with custom array or index types to implement custom indexing behavior.

More complex types of indexes may require more information about the dimension they index. To support such cases, to_indices(A, I) calls to_indices(A, axes(A), I), which then recursively traverses the specified tuple of indexes and dimensional indexes of A. Thus, not all types of indexes are guaranteed to extend to `Base.to_index'.

Examples

julia> A = zeros(1,2,3,4);

julia> to_indices(A, (1,1,2,2))
(1, 1, 2, 2)

julia> to_indices(A, (1,1,2,20)) # без проверки границ
(1, 1, 2, 20)

julia> to_indices(A, (CartesianIndex((1,)), 2, CartesianIndex((3,4)))) # необычный индекс
(1, 2, 3, 4)

julia> to_indices(A, ([1,1], 1:2, 3, 4))
([1, 1], 1:2, 3, 4)

julia> to_indices(A, (1,2)) # без проверки формы
(1, 2)
checkbounds(Bool, A, I...)

Returns true if the specified indexes I are located within the boundaries of the specified array A'. The subtypes of `AbstractArray should specialize this method if they need to implement custom boundary checking behavior. However, in many cases, you can use the indexes A and the function checkindex.

See also the description checkindex.

Examples

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...)

Returns an error if the specified indexes I are outside the boundaries of the specified array `A'.

checkindex(Bool, inds::AbstractUnitRange, index)

Returns true if the specified index is within the bounds of `inds'. Custom types that could act as indexes for all arrays can extend this method to introduce a specialized implementation of bounds checking.

See also the description checkbounds.

Examples

julia> checkindex(Bool, 1:20, 8)
true

julia> checkindex(Bool, 1:20, 21)
false
elsize(type)

Calculates the memory step in bytes between consecutive elements 'eltype`, stored inside the specified type if the array elements are stored densely with a uniform linear step.

Examples

julia> Base.elsize(rand(Float32, 10))
4

Representations (subarrays and other types of representations)

A "view" is a data structure that works as an array (it is a subtype of an "AbstractArray"), although the data is actually taken from another array.

For example, if x is an array and the expression v = @view x[1:10] is given, then v works as an array of 10 elements, although when accessing data, the first 10 elements of x are actually accessed. When writing to a representation, for example, v[3] = 2, data is written directly to the base array x (in this case, the element x[3] is changed).

When you receive a slice, for example, x[1:10], a copy is created in Julia by default. The expression @view x[1:10] allows you to change this behavior and create a view. The macro @views can be applied to an entire block of code (for example, @views function foo() .... end or @views begin ... end). At the same time, all operations of taking a slice in this block are changed so that representations are created. Sometimes it may be faster to create a copy, and sometimes it may be faster to use a view, as described in Performance Tips.

view(A, inds...)

Similar to getindex, but returns a simplified array that "lazily" references (or is actually a _ representation_) the parent array A at a given index or indexes inds instead of actively extracting elements or building a copied subset. When calling getindex or setindex! for the return value (often SubArray) indexes are calculated to access or dynamically modify the parent array. The behavior will be undefined if the shape of the parent array is changed after calling view, since checking the boundaries of the parent array is not performed. For example, a segmentation fault may occur.

Some immutable parent arrays (such as ranges) may, under certain circumstances, simply recalculate the new array instead of returning a SubArray if this is efficient and provides compatible semantics.

Compatibility: Julia 1.6

In Julia 1.6 or later, view can be called for AbstractString, which returns `SubString'.

Examples

julia> A = [1 2; 3 4]
2×2 Matrix{Int64}:
 1  2
 3  4

julia> b = view(A, :, 1)
2-element view(::Matrix{Int64}, :, 1) with eltype Int64:
 1
 3

julia> fill!(b, 0)
2-element view(::Matrix{Int64}, :, 1) with eltype Int64:
 0
 0

julia> A # Обратите внимание, что A изменился, хотя был изменен b
2×2 Matrix{Int64}:
 0  2
 0  4

julia> view(2:5, 2:3) # возвращает диапазон, так как тип является неизменяемым
3:4
@view A[inds...]

Converts the indexing expression A[inds...] in an equivalent call view.

It can be applied directly to only one indexing expression. It is especially useful for expressions that contain special indexing syntaxes begin or end, such as A[begin, 2:end-1] (since the usual function view does not support them).

Note that @view cannot be used as a regular assignment target (for example, @view(A[1, 2:end]) = ...), as well as undecorated indexed assignment (A[1, 2:end] = ...) or translated indexed assignment (A[1, 2:end] .= ...) will not create a copy. However, it can be useful for updating translated assignments, such as @view(A[1, 2:end]).+= 1, because this is a simple syntax for @view(A[1, 2:end]).= @view(A[1, 2:end]) + 1, and the indexing expression on the right side would otherwise create a copy without @view.

See also the description @views with information about switching the entire code block to using views for non-scalar indexing.

Compatibility: Julia 1.5

To use begin in an indexing expression to reference the first index, a Julia version at least 1.5 is required.

Examples

julia> A = [1 2; 3 4]
2×2 Matrix{Int64}:
 1  2
 3  4

julia> b = @view A[:, 1]
2-element view(::Matrix{Int64}, :, 1) with eltype Int64:
 1
 3

julia> fill!(b, 0)
2-element view(::Matrix{Int64}, :, 1) with eltype Int64:
 0
 0

julia> A
2×2 Matrix{Int64}:
 0  2
 0  4
@views expression

Converts each array slice operation into a given expression (which can be a begin/end block, loop, function, etc.) to return a representation. Scalar indexes, non-array types, and explicit calls getindex (as opposed to array[...]) are not affected.

Similarly, @views converts string slices into views. SubString.

The macro @views affects only the expressions array[...], which are explicitly used in the specified expression, rather than the array slicing operation that occurs in the functions called by this code.

Compatibility: Julia 1.5

The use of begin in an indexing expression to refer to the first index was implemented in Julia 1.4, but @views has only been supported since Julia 1.5.

Examples

julia> A = zeros(3, 3);

julia> @views for row in 1:3
           b = A[row, :] # b — это представление, а не копия
           b .= row      # присваиваем каждый элемент индексу строки
       end

julia> A
3×3 Matrix{Float64}:
 1.0  1.0  1.0
 2.0  2.0  2.0
 3.0  3.0  3.0
parent(A)

Returns the base parent object of the view. This is the parent object of objects of type SubArray, SubString, ReshapedArray or LinearAlgebra.Transpose is what was passed as an argument to view, reshape, transpose, etc. when creating the object. If the input object is not an enclosed object, it returns by itself. If the input object is encased multiple times, only the outermost layer will be removed.

Examples

julia> A = [1 2; 3 4]
2×2 Matrix{Int64}:
 1  2
 3  4

julia> V = view(A, 1:2, :)
2×2 view(::Matrix{Int64}, 1:2, :) with eltype Int64:
 1  2
 3  4

julia> parent(V)
2×2 Matrix{Int64}:
 1  2
 3  4
parentindices(A)

Returns indexes in parent, which correspond to the representation of the array A.

Examples

julia> A = [1 2; 3 4];

julia> V = view(A, 1, :)
2-element view(::Matrix{Int64}, 1, :) with eltype Int64:
 1
 2

julia> parentindices(V)
(1, Base.Slice(Base.OneTo(2)))
selectdim(A, d::Integer, i)

Returns a representation of all data A, where the index for dimension d is equal to i.

Equivalent to view(A,:,:,...,i,:,:,...), where i is in position `d'.

See also the description eachslice.

Examples

julia> A = [1 2 3 4; 5 6 7 8]
2×4 Matrix{Int64}:
 1  2  3  4
 5  6  7  8

julia> selectdim(A, 2, 3)
2-element view(::Matrix{Int64}, :, 3) with eltype Int64:
 3
 7

julia> selectdim(A, 2, 3:4)
2×2 view(::Matrix{Int64}, :, 3:4) with eltype Int64:
 3  4
 7  8
reinterpret(::Type{Out}, x::In)

Changes the interpretation of the binary data type in the value isbits x to the interpretation of the type isbits Out'. The size of the `Out (excluding padding) must be the same as that of the x type. For example, reinterpret(Float32, UInt32(7))`interprets 4 bytes related to `UInt32(7) as Float32. Note that reinterpret(In, reinterpret(Out, x)) === x

julia> reinterpret(Float32, UInt32(7))
1.0f-44

julia> reinterpret(NTuple{2, UInt8}, 0x1234)
(0x34, 0x12)

julia> reinterpret(UInt16, (0x34, 0x12))
0x1234

julia> reinterpret(Tuple{UInt16, UInt8}, (0x01, 0x0203))
(0x0301, 0x02)

Padding is handled differently than when using reinterpret(::DataType, ::AbstractArray).

Be careful if some combinations of bits in Out are not considered valid and are prohibited by the type’s constructors and methods. Without additional verification, the behavior may be unexpected.


reinterpret(T::DataType, A::AbstractArray)

Creates a representation of an array with the same binary data as in the specified array, but with T as the element type.

This function also works with "deferred" arrays, whose elements are not calculated until they are explicitly extracted. For example, reinterpret in the range 1:6 works the same way as for the dense vector collect(1:6):

julia> reinterpret(Float32, UInt32[1 2 3 4 5])
1×5 reinterpret(Float32, ::Matrix{UInt32}):
 1.0f-45  3.0f-45  4.0f-45  6.0f-45  7.0f-45

julia> reinterpret(Complex{Int}, 1:6)
3-element reinterpret(Complex{Int64}, ::UnitRange{Int64}):
 1 + 2im
 3 + 4im
 5 + 6im

If the location of the padding bits for T and eltype(A) does not match, the resulting array will be read-only or write-only to prevent invalid bits from being written or read, respectively.

julia> a = reinterpret(Tuple{UInt8, UInt32}, UInt32[1, 2])
1-element reinterpret(Tuple{UInt8, UInt32}, ::Vector{UInt32}):
 (0x01, 0x00000002)

julia> a[1] = 3
ERROR: Padding of type Tuple{UInt8, UInt32} is not compatible with type UInt32.

julia> b = reinterpret(UInt32, Tuple{UInt8, UInt32}[(0x01, 0x00000002)]); # при отображении будет выдана ошибка

julia> b[1]
ERROR: Padding of type UInt32 is not compatible with type Tuple{UInt8, UInt32}.

reinterpret(reshape, T, A::AbstractArray{S}) -> B

Changes the interpretation of type A when consuming or adding a "channel dimension".

If sizeof(T) = n*sizeof(S) for n>1, then the first dimension of A should have size n, and the first dimension of A is missing in B. Conversely, if sizeof(S) = n*sizeof(T) for n>1, B gets a new first dimension of size n'. The dimension does not change if `sizeof(T) == sizeof(S).

Compatibility: Julia 1.6

This method requires a Julia version of at least 1.6.

Examples

julia> A = [1 2; 3 4]
2×2 Matrix{Int64}:
 1  2
 3  4

julia> reinterpret(reshape, Complex{Int}, A)    # результатом является вектор
2-element reinterpret(reshape, Complex{Int64}, ::Matrix{Int64}) with eltype Complex{Int64}:
 1 + 3im
 2 + 4im

julia> a = [(1,2,3), (4,5,6)]
2-element Vector{Tuple{Int64, Int64, Int64}}:
 (1, 2, 3)
 (4, 5, 6)

julia> reinterpret(reshape, Int, a) # the result is
a 3x2 matrix reinterpret(reshape, Int64, ::Vector{Tuple{Int64, Int64, Int64}}) with eltype Int64:
 1  4
 2  5
 3  6
reshape(A, dims...) -> AbstractArray
reshape(A, dims) -> AbstractArray

Returns an array with the same data as in A, but with different dimension sizes or number of dimensions. Two arrays use the same underlying data, so the result is mutable if and only if A is mutable and specifying the elements of one array changes the values of the other.

New dimensions can be specified either as a list of arguments or as a tuple of the form. Using :`only one dimension can be specified. In this case, its length is calculated in such a way that its product with all the specified dimensions is equal to the length of the original array `A. The total number of items should not change.

Examples

julia> A = Vector(1:16)
16-element Vector{Int64}:
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16

julia> reshape(A, (4, 4))
4×4 Matrix{Int64}:
 1  5   9  13
 2  6  10  14
 3  7  11  15
 4  8  12  16

julia> reshape(A, 2, :)
2×8 Matrix{Int64}:
 1  3  5  7   9  11  13  15
 2  4  6  8  10  12  14  16

julia> reshape(1:6, 2, 3)
2×3 reshape(::UnitRange{Int64}, 2, 3) with eltype Int64:
 1  3  5
 2  4  6
dropdims(A; dims)

Returns an array with the same data as in A, but with the deleted dimensions specified in dims. size(A,d) must be equal to 1 for each d in dims', and duplicate dimensions or numbers beyond `1:ndims(A) are prohibited.

The result uses the same basic data as A, so it is mutable if and only if A is mutable and specifying the elements of one array changes the values of the other.

See also the description reshape, vec.

Examples

julia> a = reshape(Vector(1:4),(2,2,1,1))
2×2×1×1 Array{Int64, 4}:
[:, :, 1, 1] =
 1  3
 2  4

julia> b = dropdims(a; dims=3)
2×2×1 Array{Int64, 3}:
[:, :, 1] =
 1  3
 2  4

julia> b[1,1,1] = 5; a
2×2×1×1 Array{Int64, 4}:
[:, :, 1, 1] =
 5  3
 2  4
vec(a::AbstractArray) -> AbstractVector

Transforms array a into a one-dimensional column vector. Returns a, even if it is already an AbstractVector'. The resulting array has the same underlying data as `a', so it will only be mutable if `a is mutable. In this case, when you change one array, the other will also change.

Examples

julia> a = [1 2 3; 4 5 6]
2×3 Matrix{Int64}:
 1  2  3
 4  5  6

julia> vec(a)
6-element Vector{Int64}:
 1
 4
 2
 5
 3
 6

julia> vec(1:3)
1:3

See also the description reshape and dropdims.

SubArray{T,N,P,I,L} <: AbstractArray{T,N}

The N-dimensional representation of the parent array (with type P) with element type T, limited by a tuple of indexes (with type I). The L value is true for types that support fast linear indexing, otherwise the value is `false'.

Creates a SubArray using the function view.

Concatenation and permutation

cat(A...; dims)

Performs concatenation of input arrays in the dimensions specified in `dims'.

In the d in dims dimension, the size of the output array is `sum(size(a,d) for a in A)'. In other dimensions, all input arrays must have the same size, which will also be the size of the output array in these dimensions.

If dims is a single number, the various arrays fit tightly in that dimension. If dims is an iterable object containing several dimensions, then the positions along these dimensions are simultaneously increased for each input array, filling all other places with zero. This allows you to build block diagonal matrices in the form of cat(matrices...; dims=(1,2)) and their analogues with higher dimensions.

The special case of dims=1 is 'vcat`, and dims=2 — hcat'. See also the description `hvcat, hvncat, stack and repeat.

The named argument also accepts Val(dims).

Compatibility: Julia 1.8

For multiple dimensions, dims = Val(::Tuple) was added in Julia 1.8.

Examples

Concatenation of two arrays in different dimensions:

julia> a = [1 2 3]
1×3 Matrix{Int64}:
 1  2  3

julia> b = [4 5 6]
1×3 Matrix{Int64}:
 4  5  6

julia> cat(a, b; dims=1)
2×3 Matrix{Int64}:
 1  2  3
 4  5  6

julia> cat(a, b; dims=2)
1×6 Matrix{Int64}:
 1  2  3  4  5  6

julia> cat(a, b; dims=(1, 2))
2×6 Matrix{Int64}:
 1  2  3  0  0  0
 0  0  0  4  5  6

Advanced Help

Concatenation of three-dimensional arrays:

julia> a = ones(2, 2, 3);

julia> b = ones(2, 2, 4);

julia> c = cat(a, b; dims=3);

julia> size(c) == (2, 2, 7)
true

Concatenation of arrays of different sizes:

julia> cat([1 2; 3 4], [pi, pi], fill(10, 2,3,1); dims=2)  # то же, что и hcat
2×6×1 Array{Float64, 3}:
[:, :, 1] =
 1.0  2.0  3.14159  10.0  10.0  10.0
 3.0  4.0  3.14159  10.0  10.0  10.0

Building a block diagonal matrix:

julia> cat(true, trues(2,2), trues(4)', dims=(1,2))  # блочно-диагональная
4×7 Matrix{Bool}:
 1  0  0  0  0  0  0
 0  1  1  0  0  0  0
 0  1  1  0  0  0  0
 0  0  0  1  1  1  1
julia> cat(1, [2], [3;;]; dims=Val(2))
1×3 Matrix{Int64}:
 1  2  3

cat does not combine two strings; for this, you can use *.

julia> a = "aaa";

julia> b = "bbb";

julia> cat(a, b; dims=1)
2-element Vector{String}:
 "aaa"
 "bbb"

julia> cat(a, b; dims=2)
1×2 Matrix{String}:
 "aaa"  "bbb"

julia> a * b
"aaabbb"
vcat(A...)

Performs concatenation of arrays or numbers vertically. Equivalent to cat(A...; dims=1) and the syntax of [a; b; c].

To concatenate a large vector of arrays, reduce(vcat, A) calls an efficient method when A isa AbstractVector{<:AbstractVecOrMat}, instead of working in pairs.

See also the description hcat, Iterators.flatten and stack.

Examples

julia> v = vcat([1,2], [3,4])
4-element Vector{Int64}:
 1
 2
 3
 4

julia> v == vcat(1, 2, [3,4])  # принимает числа
true

julia> v == [1; 2; [3,4]]  # синтаксис для той же операции
true

julia> summary(ComplexF64[1; 2; [3,4]])  # синтаксис для указания типа элемента
"4-element Vector{ComplexF64}"

julia> vcat(range(1, 2, length=3))  # собирает «ленивые» диапазоны
3-element Vector{Float64}:
 1.0
 1.5
 2.0

julia> two = ([10, 20, 30]', Float64[4 5 6; 7 8 9])  # вектор строки и матрица
([10 20 30], [4.0 5.0 6.0; 7.0 8.0 9.0])

julia> vcat(two...)
3×3 Matrix{Float64}:
 10.0  20.0  30.0
  4.0   5.0   6.0
  7.0   8.0   9.0

julia> vs = [[1, 2], [3, 4], [5, 6]];

julia> reduce(vcat, vs)  # эффективнее, чем vcat(vs...)
6-element Vector{Int64}:
 1
 2
 3
 4
 5
 6

julia> ans == collect(Iterators.flatten(vs))
true
hcat(A...)

Performs concatenation of arrays or numbers horizontally. Equivalent to cat(A...; dims=2) and the syntax of [a b c] or [a;; b;; c].

To concatenate a large set of arrays, reduce(hcat, A) calls an efficient method if A isa AbstractVector{<:AbstractVecOrMat}. For a vector of vectors, it can also be written as stack(A).

See also the description 'vcat` and hvcat.

Examples

julia> hcat([1,2], [3,4], [5,6])
2×3 Matrix{Int64}:
 1  3  5
 2  4  6

julia> hcat(1, 2, [30 40], [5, 6, 7]')  # принимает числа
1×7 Matrix{Int64}:
 1  2  30  40  5  6  7

julia> ans == [1 2 [30 40] [5, 6, 7]']  # синтаксис для той же операции
true

julia> Float32[1 2 [30 40] [5, 6, 7]']  # синтаксис для указания типа элемента
1×7 Matrix{Float32}:
 1.0  2.0  30.0  40.0  5.0  6.0  7.0

julia> ms = [zeros(2,2), [1 2; 3 4], [50 60; 70 80]];

julia> reduce(hcat, ms)  # эффективнее, чем hcat(ms...)
2×6 Matrix{Float64}:
 0.0  0.0  1.0  2.0  50.0  60.0
 0.0  0.0  3.0  4.0  70.0  80.0

julia> stack(ms) |> summary  # отличается от вектора матриц
"2×2×3 Array{Float64, 3}"

julia> hcat(Int[], Int[], Int[])  # пустые векторы, каждый размером (0,)
0×3 Matrix{Int64}

julia> hcat([1.1, 9.9], Matrix(undef, 2, 0))  # hcat с пустой матрицей 2×0
2×1 Matrix{Any}:
 1.1
 9.9
hvcat(blocks_per_row::Union{Tuple{Vararg{Int}}, Int}, values...)

Horizontal and vertical concatenation in one call. This function is called for the block matrix syntax. The first argument specifies the number of arguments to concatenate in each line of the block. If the first argument is a single integer n, it is assumed that all block rows have n block columns.

Examples

julia> a, b, c, d, e, f = 1, 2, 3, 4, 5, 6
(1, 2, 3, 4, 5, 6)

julia> [a b c; d e f]
2×3 Matrix{Int64}:
 1  2  3
 4  5  6

julia> hvcat((3,3), a,b,c,d,e,f)
2×3 Matrix{Int64}:
 1  2  3
 4  5  6

julia> [a b; c d; e f]
3×2 Matrix{Int64}:
 1  2
 3  4
 5  6

julia> hvcat((2,2,2), a,b,c,d,e,f)
3×2 Matrix{Int64}:
 1  2
 3  4
 5  6
julia> hvcat((2,2,2), a,b,c,d,e,f) == hvcat(2, a,b,c,d,e,f)
true
hvncat(dim::Int, row_first, values...)
hvncat(dims::Tuple{Vararg{Int}}, row_first, values...)
hvncat(shape::Tuple{Vararg{Tuple}}, row_first, values...)

Horizontal, vertical, and n-dimensional concatenation in a single values call.

This function is called for the block matrix syntax. The first argument either specifies a form of concatenation, similar to hvcat, in the form of a tuple of tuples, or dimensions that determine the key number of elements on each axis, and is used to determine the output dimensions. The `dims' form is more productive and is used by default when the concatenation operation contains the same number of elements on each axis (for example, [a b; c d;

e f ; g h]). The shape is used when the number of elements on each axis is not balanced (for example, [a b ; c]). An unbalanced syntax requires additional verification costs. The dim shape is an optimization for concatenation in only one dimension. row_first specifies the ordering method for values'. The values of the first and second `shape elements are also swapped based on `row_first'.

Examples

julia> a, b, c, d, e, f = 1, 2, 3, 4, 5, 6
(1, 2, 3, 4, 5, 6)

julia> [a b c;;; d e f]
1×3×2 Array{Int64, 3}:
[:, :, 1] =
 1  2  3

[:, :, 2] =
 4  5  6

julia> hvncat((2,1,3), false, a,b,c,d,e,f)
2×1×3 Array{Int64, 3}:
[:, :, 1] =
 1
 2

[:, :, 2] =
 3
 4

[:, :, 3] =
 5
 6

julia> [a b;;; c d;;; e f]
1×2×3 Array{Int64, 3}:
[:, :, 1] =
 1  2

[:, :, 2] =
 3  4

[:, :, 3] =
 5  6

julia> hvncat(((3, 3), (3, 3), (6,)), true, a, b, c, d, e, f)
1×3×2 Array{Int64, 3}:
[:, :, 1] =
 1  2  3

[:, :, 2] =
 4  5  6

Examples for constructing arguments

[a b c ; d e f ;;;
 g h i ; j k l ;;;
 m n o ; p q r ;;;
 s t u ; v w x]
⇒ dims = (2, 3, 4)

[a b ; c ;;; d ;;;;]
 ___   _     _
 2     1     1 = elements in each row (2, 1, 1)
 _______     _
 3           1 = elements in each column (3, 1)
 _____________
 4             = elements in each 3d slice (4,)
 _____________
 4             = elements in each 4d slice (4,)
⇒ shape = ((2, 1, 1), (3, 1), (4,), (4,)) with `row_first` = true
stack(iter; [dims])

Combines a collection of arrays (or other iterable objects) of the same size into one larger array, arranging them in one or more new dimensions.

By default, the axes of the elements are positioned first, which gives size(result) = (size(first(iter))..., size(iter)...). In this case, the same order of elements is formed as when using Iterators.flatten(iter).

When using the named argument dims::Integer, the i’th iteration element (`iter) becomes a slice. selectdim(result, dims, i), so that size(result, dims) == length(iter). In this case, the stack' changes the function action. 'eachslice to reverse with the same `dims'.

Various functions cat can also combine arrays. However, they all extend existing (possibly trivial) array dimensions rather than placing arrays in new dimensions. They also accept arrays as separate arguments rather than as a single collection.

Compatibility: Julia 1.9

This feature requires a Julia version of at least 1.9.

Examples

julia> vecs = (1:2, [30, 40], Float32[500, 600]);

julia> mat = stack(vecs)
2×3 Matrix{Float32}:
 1.0  30.0  500.0
 2.0  40.0  600.0

julia> mat == hcat(vecs...) == reduce(hcat, collect(vecs))
true

julia> vec(mat) == vcat(vecs...) == reduce(vcat, collect(vecs))
true

julia> stack(zip(1:4, 10:99))  # принимает любые итераторы итераторов
2×4 Matrix{Int64}:
  1   2   3   4
 10  11  12  13

julia> vec(ans) == collect(Iterators.flatten(zip(1:4, 10:99)))
true

julia> stack(vecs; dims=1)  # В отличие от любой функции cat, 1-я ось vecs[1] является 2-й осью результата
3×2 Matrix{Float32}:
   1.0    2.0
  30.0   40.0
 500.0  600.0

julia> x = rand(3,4);

julia> x == stack(eachcol(x)) == stack(eachrow(x), dims=1) # the inverse of each slice value
true

Examples of higher dimensions:

julia> A = rand(5, 7, 11);

julia> E = eachslice(A, dims=2);  # вектор матриц

julia> (element = size(first(E)), container = size(E))
(element = (5, 11), container = (7,))

julia> stack(E) |> size
(5, 11, 7)

julia> stack(E) == stack(E; dims=3) == cat(E...; dims=3)
true

julia> A == stack(E; dims=2)
true

julia> M = (fill(10i+j, 2, 3) for i in 1:5, j in 1:7);

julia> (element = size(first(M)), container = size(M))
(element = (2, 3), container = (5, 7))

julia> stack(M) |> size  # все измерения сохраняются
(2, 3, 5, 7)

julia> stack(M; dims=1) |> size  # vec(container) в dims=1
(35, 2, 3)

julia> hvcat(5, M...) |> size  # hvcat размещает матрицы рядом друг с другом
(14, 15)

stack(f, args...; [dims])

Applies a function to each element of the collection and puts the result on the stack. Or to multiple collections combined (zip) together.

The function must return arrays (or tuples, or other iterators) of the same size. They become slices of the result, each of which is divided by dims (if specified) or by default by the last dimension.

See also the description mapslices and eachcol.

Examples

julia> stack(c -> (c, c-32), "julia")
2×5 Matrix{Char}:
 'j'  'u'  'l'  'i'  'a'
 'J'  'U'  'L'  'I'  'A'

julia> stack(eachrow([1 2 3; 4 5 6]), (10, 100); dims=1) do row, n
         vcat(row, row .* n, row ./ n)
       end
2×9 Matrix{Float64}:
 1.0  2.0  3.0   10.0   20.0   30.0  0.1   0.2   0.3
 4.0  5.0  6.0  400.0  500.0  600.0  0.04  0.05  0.06
vect(X...)

Creates Vector with the element type calculated from the promote_typeof argument containing the argument list.

Examples

julia> a = Base.vect(UInt8(1), 2.5, 1//2)
3-element Vector{Float64}:
 1.0
 2.5
 0.5
circshift(A, shifts)

Performs a circular shift, i.e. rotation, of the data in the array. The second argument is a tuple or vector specifying the amount of shift in each dimension, or an integer for shifting only in the first dimension.

See also the description circshift!, circcopy!, bitrotate, <<.

Examples

julia> b = reshape(Vector(1:16), (4,4))
4×4 Matrix{Int64}:
 1  5   9  13
 2  6  10  14
 3  7  11  15
 4  8  12  16

julia> circshift(b, (0,2))
4×4 Matrix{Int64}:
  9  13  1  5
 10  14  2  6
 11  15  3  7
 12  16  4  8

julia> circshift(b, (-1,0))
4×4 Matrix{Int64}:
 2  6  10  14
 3  7  11  15
 4  8  12  16
 1  5   9  13

julia> a = BitArray([true, true, false, false, true])
5-element BitVector:
 1
 1
 0
 0
 1

julia> circshift(a, 1)
5-element BitVector:
 1
 1
 1
 0
 0

julia> circshift(a, -1)
5-element BitVector:
 1
 0
 0
 1
 1
circshift!(dest, src, shifts)

Performs a circular shift, i.e. rotation, of the data in src' while saving the result in `dest'. `shifts sets the amount of shift in each dimension.

If any modified argument is placed in the same memory area as any other argument, the behavior may be unexpected.

See also the description circshift.

circcopy!(dest, src)

Copies src to dest', indexing each dimension modulo its length. `src and dest must have the same size, but can be shifted in indexes; any shift results in (circular) wrapping. If the arrays have overlapping indexes, then in the overlap area dest matches `src'.

If any modified argument is placed in the same memory area as any other argument, the behavior may be unexpected.

See also the description circshift.

Examples

julia> src = reshape(Vector(1:16), (4,4))
4×4 Array{Int64,2}:
 1  5   9  13
 2  6  10  14
 3  7  11  15
 4  8  12  16

julia> dest = OffsetArray{Int}(undef, (0:3,2:5))

julia> circcopy!(dest, src)
OffsetArrays.OffsetArray{Int64,2,Array{Int64,2}} with indices 0:3×2:5:
 8  12  16  4
 5   9  13  1
 6  10  14  2
 7  11  15  3

julia> dest[1:3,2:4] == src[1:3,2:4]
true
findall(A)

Returns a vector I of true indexes or A keys. If there are no such elements of `A', an empty array is returned. To search for other types of values, pass the predicate as the first argument.

The indexes or keys are of the same type as the indexes and keys returned by the methods. keys(A) and pairs(A).

See also the description findfirst, searchsorted.

Examples

julia> A = [true, false, false, true]
4-element Vector{Bool}:
 1
 0
 0
 1

julia> findall(A)
2-element Vector{Int64}:
 1
 4

julia> A = [true false; false true]
2×2 Matrix{Bool}:
 1  0
 0  1

julia> findall(A)
2-element Vector{CartesianIndex{2}}:
 CartesianIndex(1, 1)
 CartesianIndex(2, 2)

julia> findall(falses(3))
Int64[]
findall(f::Function, A)

Returns the vector I of indexes or keys A, where f(A[I]) returns `true'. If there are no such elements of `A', an empty array is returned.

The indexes or keys are of the same type as the indexes and keys returned by the methods. keys(A) and pairs(A).

Examples

julia> x = [1, 3, 4]
3-element Vector{Int64}:
 1
 3
 4

julia> findall(isodd, x)
2-element Vector{Int64}:
 1
 2

julia> A = [1 2 0; 3 4 0]
2×3 Matrix{Int64}:
 1  2  0
 3  4  0
julia> findall(isodd, A)
2-element Vector{CartesianIndex{2}}:
 CartesianIndex(1, 1)
 CartesianIndex(2, 1)

julia> findall(!iszero, A)
4-element Vector{CartesianIndex{2}}:
 CartesianIndex(1, 1)
 CartesianIndex(2, 1)
 CartesianIndex(1, 2)
 CartesianIndex(2, 2)

julia> d = Dict(:A => 10, :B => -1, :C => 0)
Dict{Symbol, Int64} with 3 entries:
  :A => 10
  :B => -1
  :C => 0

julia> findall(x -> x >= 0, d)
2-element Vector{Symbol}:
 :A
 :C
findfirst(A)

Returns the index or key of the first true value in `A'. Returns `nothing' if no such value is found. To search for other types of values, pass the predicate as the first argument.

The indexes or keys are of the same type as the indexes and keys returned by the methods. keys(A) and pairs(A).

See also the description findall, findnext, findlast, searchsortedfirst.

Examples

julia> A = [false, false, true, false]
4-element Vector{Bool}:
 0
 0
 1
 0

julia> findfirst(A)
3

julia> findfirst(falses(3)) # returns nothing, but is not output to the REPL

julia> A = [false false; true false]
2×2 Matrix{Bool}:
 0  0
 1  0

julia> findfirst(A)
CartesianIndex(2, 1)
findfirst(predicate::Function, A)

Returns the index or key of the first element A, for which predict returns `true'. Returns `nothing' if there is no such element.

The indexes or keys are of the same type as the indexes and keys returned by the methods. keys(A) and pairs(A).

Examples

julia> A = [1, 4, 2, 2]
4-element Vector{Int64}:
 1
 4
 2
 2

julia> findfirst(iseven, A)
2

julia> findfirst(x -> x>10, A) # возвращает nothing, но не выводится в REPL

julia> findfirst(isequal(4), A)
2

julia> A = [1 4; 2 2]
2×2 Matrix{Int64}:
 1  4
 2  2

julia> findfirst(iseven, A)
CartesianIndex(2, 1)
findlast(A)

Returns the index or key of the last true value in A'. Returns `nothing' if there is no 'true value in A.

The indexes or keys are of the same type as the indexes and keys returned by the methods. keys(A) and pairs(A).

See also the description findfirst, findprev, findall.

Examples

julia> A = [true, false, true, false]
4-element Vector{Bool}:
 1
 0
 1
 0

julia> findlast(A)
3

julia> A = falses(2,2);

julia> findlast(A) # возвращает nothing, но не выводится в REPL

julia> A = [true false; true false]
2×2 Matrix{Bool}:
 1  0
 1  0

julia> findlast(A)
CartesianIndex(2, 1)
findlast(predicate::Function, A)

Returns the index or key of the last element of A, for which predict returns true'. Returns `nothing if there is no such element.

The indexes or keys are of the same type as the indexes and keys returned by the methods. keys(A) and pairs(A).

Examples

julia> A = [1, 2, 3, 4]
4-element Vector{Int64}:
 1
 2
 3
 4

julia> findlast(isodd, A)
3

julia> findlast(x -> x > 5, A) # возвращает nothing, но не выводится в REPL

julia> A = [1 2; 3 4]
2×2 Matrix{Int64}:
 1  2
 3  4

julia> findlast(isodd, A)
CartesianIndex(2, 1)
findnext(A, i)

Finds the next index after the i element true in the array A or including it, or nothing if the index is not found.

The indexes are of the same type as the indexes returned by the methods. keys(A) and pairs(A).

Examples

julia> A = [false, false, true, false]
4-element Vector{Bool}:
 0
 0
 1
 0

julia> findnext(A, 1)
3

julia> findnext(A, 4) # возвращает nothing, но не выводится в REPL

julia> A = [false false; true false]
2×2 Matrix{Bool}:
 0  0
 1  0

julia> findnext(A, CartesianIndex(1, 1))
CartesianIndex(2, 1)
findnext(predicate::Function, A, i)

Finds the next index after or including the i element A, for which predict' returns `true or nothing' if the index is not found. Works for arrays, strings, and most other collections that support `getindex, keys(A) and nextind.

The indexes are of the same type as the indexes returned by the methods. keys(A) and pairs(A).

Examples

julia> A = [1, 4, 2, 2];

julia> findnext(isodd, A, 1)
1

julia> findnext(isodd, A, 2) # возвращает nothing, но не выводится в REPL

julia> A = [1 4; 2 2];

julia> findnext(isodd, A, CartesianIndex(1, 1))
CartesianIndex(1, 1)

julia> findnext(isspace, "a b c", 3)
4
findprev(A, i)

Finds the previous index up to or including the i element true in the array A, or nothing if the index is not found.

The indexes are of the same type as the indexes returned by the methods. keys(A) and pairs(A).

See also the description findnext, findfirst, findall.

Examples

julia> A = [false, false, true, true]
4-element Vector{Bool}:
 0
 0
 1
 1

julia> findprev(A, 3)
3

julia> findprev(A, 1) # возвращает nothing, но не выводится в REPL

julia> A = [false false; true true]
2×2 Matrix{Bool}:
 0  0
 1  1

julia> findprev(A, CartesianIndex(2, 1))
CartesianIndex(2, 1)
findprev(predicate::Function, A, i)

Finds the previous index up to i of the element A, for which predict' returns `true', or including it, or `nothing' if the index is not found. Works for arrays, strings, and most other collections that support `getindex, keys(A) and nextind.

The indexes are of the same type as the indexes returned by the methods. keys(A) and pairs(A).

Examples

julia> A = [4, 6, 1, 2]
4-element Vector{Int64}:
 4
 6
 1
 2

julia> findprev(isodd, A, 1) # возвращает nothing, но не выводится в REPL

julia> findprev(isodd, A, 3)
3

julia> A = [4 6; 1 2]
2×2 Matrix{Int64}:
 4  6
 1  2

julia> findprev(isodd, A, CartesianIndex(1, 2))
CartesianIndex(2, 1)

julia> findprev(isspace, "a b c", 3)
2
permutedims(A::AbstractArray, perm)
permutedims(A::AbstractMatrix)

Resets the dimensions (axes) of array A'. `perm is a tuple or vector of ndims(A) integers defining a permutation.

If A is a two-dimensional array (AbstractMatrix), then perm defaults to (2,1), swapping the two axes A (rows and columns of the matrix). The difference from transpose is that this operation is not recursive, which is especially useful in the case of arrays of non-numeric values (for which the recursive function transpose returns an error) and/or two-dimensional arrays that do not represent linear operators.

For one-dimensional arrays, use the method permutedims(v::AbstractVector), which returns a one-line "matrix".

See also the description permutedims!, PermutedDimsArray, transpose and invperm.

Examples

Two-dimensional arrays:

Unlike transpose, permutedims can be used to permute rows and columns of two-dimensional arrays of arbitrary non-numeric elements, such as strings:

julia> A = ["a" "b" "c"
            "d" "e" "f"]
2×3 Matrix{String}:
 "a"  "b"  "c"
 "d"  "e"  "f"

julia> permutedims(A)
3×2 Matrix{String}:
 "a"  "d"
 "b"  "e"
 "c"  "f"

permutedims produces results that differ from those of transpose for matrices whose elements are themselves numeric matrices.:

julia> a = [1 2; 3 4];

julia> b = [5 6; 7 8];

julia> c = [9 10; 11 12];

julia> d = [13 14; 15 16];

julia> X = [[a] [b]; [c] [d]]
2×2 Matrix{Matrix{Int64}}:
 [1 2; 3 4]     [5 6; 7 8]
 [9 10; 11 12]  [13 14; 15 16]

julia> permutedims(X)
2×2 Matrix{Matrix{Int64}}:
 [1 2; 3 4]  [9 10; 11 12]
 [5 6; 7 8]  [13 14; 15 16]

julia> transpose(X)
2×2 transpose(::Matrix{Matrix{Int64}}) with eltype Transpose{Int64, Matrix{Int64}}:
 [1 3; 2 4]  [9 11; 10 12]
 [5 7; 6 8]  [13 15; 14 16]

Multidimensional arrays

julia> A = reshape(Vector(1:8), (2,2,2))
2×2×2 Array{Int64, 3}:
[:, :, 1] =
 1  3
 2  4

[:, :, 2] =
 5  7
 6  8

julia> perm = (3, 1, 2); # последнее измерение размещается первым

julia> B = permutedims(A, perm)
2×2×2 Array{Int64, 3}:
[:, :, 1] =
 1  2
 5  6

[:, :, 2] =
 3  4
 7  8

julia> A == permutedims(B, invperm(perm)) # обратная перестановка
true

For each dimension i in B = permutedims(A, perm)`the corresponding dimension of `A will be perm[i]. This means that the equality size(B, i) == size(A, perm[i]) holds.

julia> A = randn(5, 7, 11, 13);

julia> perm = [4, 1, 3, 2];

julia> B = permutedims(A, perm);

julia> size(B)
(13, 5, 11, 7)

julia> size(A)[perm] == ans
true

permutedims(v::AbstractVector)

Changes the shape of the vector v to a lowercase matrix 1 × length(v). The difference from transpose is that this operation is not recursive, which is especially useful in the case of arrays of non-numeric values (for which the recursive function `transpose' may throw an error).

Examples

Unlike transpose, permutedims can be used for vectors of arbitrary non-numeric elements, such as strings:

julia> permutedims(["a", "b", "c"])
1×3 Matrix{String}:
 "a"  "b"  "c"

For vectors of numbers, permutedims(v) works in much the same way as transpose(v), except that the return type differs (used reshape, not the representation of LinearAlgebra.Transpose', although in both cases the same memory area is used as for the original array `v):

julia> v = [1, 2, 3, 4]
4-element Vector{Int64}:
 1
 2
 3
 4

julia> p = permutedims(v)
1×4 Matrix{Int64}:
 1  2  3  4

julia> r = transpose(v)
1×4 transpose(::Vector{Int64}) with eltype Int64:
 1  2  3  4

julia> p == r
true

julia> typeof(r)
Transpose{Int64, Vector{Int64}}

julia> p[1] = 5; r[2] = 6; # при изменении p или r также изменяется v

julia> v # размещается в одной области памяти с p и r
4-element Vector{Int64}:
 5
 6
 3
 4

However, permutedims produces results that differ from those of `transpose' for vectors whose elements are themselves numeric matrices.:

julia> V = [[[1 2; 3 4]]; [[5 6; 7 8]]]
2-element Vector{Matrix{Int64}}:
 [1 2; 3 4]
 [5 6; 7 8]

julia> permutedims(V)
1×2 Matrix{Matrix{Int64}}:
 [1 2; 3 4]  [5 6; 7 8]

julia> transpose(V)
1×2 transpose(::Vector{Matrix{Int64}}) with eltype Transpose{Int64, Matrix{Int64}}:
 [1 3; 2 4]  [5 7; 6 8]
permutedims!(dest, src, perm)

Stops measuring the src array and saves the result in the dest array. perm is a vector indicating a permutation of length ndims(src)'. The pre-allocated `dest array must have size(dest) == size(src)[perm] and be completely overwritten. In-place permutation is not supported, and if src and dest have overlapping memory areas, unexpected results should be expected.

See also the description permutedims.

PermutedDimsArray(A, perm) -> B

For a given AbstractArray, A creates a representation of B in such a way that the dimensions appear to be rearranged. Similar to permutedims, except that no copying is performed (B uses the same memory area as `A').

See also the description permutedims' and `invperm.

Examples

julia> A = rand(3,5,4);

julia> B = PermutedDimsArray(A, (3,1,2));

julia> size(B)
(4, 3, 5)

julia> B[3,1,2] == A[1,2,3]
true
promote_shape(s1, s2)

Checks two array shapes for compatibility, allowing finite single dimensions, and returns the shape that has more dimensions.

Examples

julia> a = fill(1, (3,4,1,1,1));

julia> b = fill(1, (3,4));

julia> promote_shape(a,b)
(Base.OneTo(3), Base.OneTo(4), Base.OneTo(1), Base.OneTo(1), Base.OneTo(1))

julia> promote_shape((2,3,1,4), (2, 3, 1, 4, 1))
(2, 3, 1, 4, 1)

Functions for working with arrays

accumulate(op, A; dims::Integer, [init])

Cumulative operation op in the dims dimension of array A (it is optional to provide dims for vectors). If necessary, you can specify the initial value of init using a named argument. See also the description accumulate! with information about using a pre-allocated output array to ensure proper performance and control the accuracy of the output data (for example, to avoid overflow).

There are specialized accumulate options for common operations. See the description cumsum and cumprod. For information about the deferred version, see the description Iterators.accumulate.

Compatibility: Julia 1.5

To use accumulate in relation to an iterator that is not related to arrays, a Julia version of at least 1.5 is required.

Examples

julia> accumulate(+, [1,2,3])
3-element Vector{Int64}:
 1
 3
 6

julia> accumulate(min, (1, -2, 3, -4, 5), init=0)
(0, -2, -2, -4, -4)

julia> accumulate(/, (2, 4, Inf), init=100)
(50.0, 12.5, 0.0)

julia> accumulate(=>, i^2 for i in 1:3)
3-element Vector{Any}:
          1
        1 => 4
 (1 => 4) => 9

julia> accumulate(+, fill(1, 3, 4))
3×4 Matrix{Int64}:
 1  4  7  10
 2  5  8  11
 3  6  9  12

julia> accumulate(+, fill(1, 2, 5), dims=2, init=100.0)
2×5 Matrix{Float64}:
 101.0  102.0  103.0  104.0  105.0
 101.0  102.0  103.0  104.0  105.0
accumulate!(op, B, A; [dims], [init])

Cumulative operation of op with A in the dimension of dims while storing the result in B'. It is not necessary to provide `dims for vectors. If the named argument init is specified, its value is used to create an accumulation.

If any modified argument is placed in the same memory area as any other argument, the behavior may be unexpected.

See also the description accumulate, cumsum! and cumprod!.

Examples

julia> x = [1, 0, 2, 0, 3];

julia> y = rand(5);

julia> accumulate!(+, y, x);

julia> y
5-element Vector{Float64}:
 1.0
 1.0
 3.0
 3.0
 6.0

julia> A = [1 2 3; 4 5 6];

julia> B = similar(A);

julia> accumulate!(-, B, A, dims=1)
2×3 Matrix{Int64}:
  1   2   3
 -3  -3  -3

julia> accumulate!(*, B, A, dims=2, init=10)
2×3 Matrix{Int64}:
 10   20    60
 40  200  1200
cumprod(A; dims::Integer)

The cumulative product in the dim dimension. See also the description cumprod! with information about using a pre-allocated output array to ensure proper performance and control the accuracy of the output data (for example, to avoid overflow).

Examples

julia> a = Int8[1 2 3; 4 5 6];

julia> cumprod(a, dims=1)
2×3 Matrix{Int64}:
 1   2   3
 4  10  18

julia> cumprod(a, dims=2)
2×3 Matrix{Int64}:
 1   2    6
 4  20  120

cumprod(itr)

The cumulative product of the iterator.

See also the description cumprod!, accumulate and cumsum.

Compatibility: Julia 1.5

To use cumprod in relation to an iterator that is not related to arrays, a Julia version of 1.5 or higher is required.

Examples

julia> cumprod(fill(1//2, 3))
3-element Vector{Rational{Int64}}:
 1//2
 1//4
 1//8

julia> cumprod((1, 2, 1, 3, 1))
(1, 2, 2, 6, 6)

julia> cumprod("julia")
5-element Vector{String}:
 "j"
 "ju"
 "jul"
 "juli"
 "julia"
cumprod!(B, A; dims::Integer)

The cumulative product of A in the dims dimension with the result stored in B. See also the description cumprod.

If any modified argument is placed in the same memory area as any other argument, the behavior may be unexpected.


cumprod!(y::AbstractVector, x::AbstractVector)

The cumulative product of the vector x with the result stored in y. See also the description cumprod.

If any modified argument is placed in the same memory area as any other argument, the behavior may be unexpected.

cumsum(A; dims::Integer)

The cumulative sum in the dims' dimension. See also the description `cumsum! with information about using a pre-allocated output array to ensure proper performance and control the accuracy of the output data (for example, to avoid overflow).

Examples

julia> a = [1 2 3; 4 5 6]
2×3 Matrix{Int64}:
 1  2  3
 4  5  6

julia> cumsum(a, dims=1)
2×3 Matrix{Int64}:
 1  2  3
 5  7  9

julia> cumsum(a, dims=2)
2×3 Matrix{Int64}:
 1  3   6
 4  9  15

The returned type of the eltype' array is `Int for signed integers less than the size of the system word, or UInt for unsigned integers less than the size of the system word. To store eltype arrays with small signed or unsigned integers, use `accumulate(+, A)'.

julia> cumsum(Int8[100, 28])
2-element Vector{Int64}:
 100
 128
julia> accumulate(+,Int8[100, 28]) 2-element Vector{Int8}: 100 -128

In the former case, the integers are widened to system word size and therefore the result is Int64[100, 128]. In the latter case, no such widening happens and integer overflow results in Int8[100, -128].


cumsum(itr)

Cumulative sum of an iterator.

See also accumulate to apply functions other than +.

Compatibility: Julia 1.5

cumsum on a non-array iterator requires at least Julia 1.5.

Examples

julia> cumsum(1:3)
3-element Vector{Int64}:
 1
 3
 6

julia> cumsum((true, false, true, false, true))
(1, 1, 2, 2, 3)

julia> cumsum(fill(1, 2) for i in 1:3)
3-element Vector{Vector{Int64}}:
 [1, 1]
 [2, 2]
 [3, 3]
cumsum!(B, A; dims::Integer)

The cumulative sum of A in the dims dimension with the result stored in B. See also the description cumsum.

If any modified argument is placed in the same memory area as any other argument, the behavior may be unexpected.

diff(A::AbstractVector)
diff(A::AbstractArray; dims::Integer)

Finite difference operator for a vector or multidimensional array `A'. In the latter case, the dimension in which the actions are to be performed should be specified using the named argument `dims'.

Compatibility: Julia 1.1

To use diff for arrays with a dimension higher than 2, a Julia version of at least 1.1 is required.

Examples

julia> a = [2 4; 6 16]
2×2 Matrix{Int64}:
 2   4
 6  16

julia> diff(a, dims=2)
2×1 Matrix{Int64}:
  2
 10

julia> diff(vec(a))
3-element Vector{Int64}:
  4
 -2
 12
repeat(A::AbstractArray, counts::Integer...)

Creates an array by repeating array A a set number of times (specified using counts) in each dimension.

See also the description fill, Iterators.repeated, Iterators.cycle.

Examples

julia> repeat([1, 2, 3], 2)
6-element Vector{Int64}:
 1
 2
 3
 1
 2
 3

julia> repeat([1, 2, 3], 2, 3)
6×3 Matrix{Int64}:
 1  1  1
 2  2  2
 3  3  3
 1  1  1
 2  2  2
 3  3  3

repeat(A::AbstractArray; inner=ntuple(Returns(1), ndims(A)), outer=ntuple(Returns(1), ndims(A)))

Creates an array by repeating the entries A. The ith element inner' sets the number of repetitions of individual entries of the ith dimension of the array `A'. The ith element `outer sets the number of repetitions of the slice in the ith dimension of the array 'A'. If the inner or outer are omitted, no repetition is performed.

Examples

julia> repeat(1:2, inner=2)
4-element Vector{Int64}:
 1
 1
 2
 2

julia> repeat(1:2, outer=2)
4-element Vector{Int64}:
 1
 2
 1
 2

julia> repeat([1 2; 3 4], inner=(2, 1), outer=(1, 3))
4×6 Matrix{Int64}:
 1  2  1  2  1  2
 1  2  1  2  1  2
 3  4  3  4  3  4
 3  4  3  4  3  4

repeat(s::AbstractString, r::Integer)

Repeats the string r times. This can be written as s^r.

See also the description of the method ^.

Examples

julia> repeat("ha", 3)
"hahaha"

repeat(c::AbstractChar, r::Integer) -> String

Repeats the character r once. This can also be done by calling c^r.

Examples

julia> repeat('A', 3)
"AAA"
rot180(A)

Rotates the matrix A by 180 degrees.

Examples

julia> a = [1 2; 3 4]
2×2 Matrix{Int64}:
 1  2
 3  4

julia> rot180(a)
2×2 Matrix{Int64}:
 4  3
 2  1

rot180(A, k)

Rotates the matrix A 180 degrees an integer number of times k'. If 'k is an even number, it is equivalent to copy.

Examples

julia> a = [1 2; 3 4]
2×2 Matrix{Int64}:
 1  2
 3  4

julia> rot180(a,1)
2×2 Matrix{Int64}:
 4  3
 2  1

julia> rot180(a,2)
2×2 Matrix{Int64}:
 1  2
 3  4
rotl90(A)

Rotates the matrix A to the left by 90 degrees.

Examples

julia> a = [1 2; 3 4]
2×2 Matrix{Int64}:
 1  2
 3  4

julia> rotl90(a)
2×2 Matrix{Int64}:
 2  4
 1  3

rotl90(A, k)

Rotates the matrix A to the left by 90 degrees counterclockwise an integer number of times k'. If 'k is a multiple of four (including zero), it is equivalent to copy.

Examples

julia> a = [1 2; 3 4]
2×2 Matrix{Int64}:
 1  2
 3  4

julia> rotl90(a,1)
2×2 Matrix{Int64}:
 2  4
 1  3

julia> rotl90(a,2)
2×2 Matrix{Int64}:
 4  3
 2  1

julia> rotl90(a,3)
2×2 Matrix{Int64}:
 3  1
 4  2

julia> rotl90(a,4)
2×2 Matrix{Int64}:
 1  2
 3  4
rotr90(A)

Rotates the matrix A to the right by 90 degrees.

Examples

julia> a = [1 2; 3 4]
2×2 Matrix{Int64}:
 1  2
 3  4

julia> rotr90(a)
2×2 Matrix{Int64}:
 3  1
 4  2

rotr90(A, k)

Rotates the matrix A to the right by 90 degrees clockwise an integer number of times k'. If 'k is a multiple of four (including zero), it is equivalent to copy.

Examples

julia> a = [1 2; 3 4]
2×2 Matrix{Int64}:
 1  2
 3  4

julia> rotr90(a,1)
2×2 Matrix{Int64}:
 3  1
 4  2

julia> rotr90(a,2)
2×2 Matrix{Int64}:
 4  3
 2  1

julia> rotr90(a,3)
2×2 Matrix{Int64}:
 2  4
 1  3

julia> rotr90(a,4)
2×2 Matrix{Int64}:
 1  2
 3  4
mapslices(f, A; dims)

Преобразует заданные измерения массива A, применяя функцию f к каждому срезу формы A[..., :, ..., :, ...], с двоеточием у каждого d в dims. Результаты конкатенируются в остальных измерениях.

Например, если dims = [1,2] и A являются четырехмерными, f вызывается в x = A[:,:,i,j] для всех i и j и f(x) становится R[:,:,i,j] в результате R.

См. также описание eachcol или eachslice, которые используются с map или stack.

Примеры

julia> A = reshape(1:30,(2,5,3))
2×5×3 reshape(::UnitRange{Int64}, 2, 5, 3) with eltype Int64:
[:, :, 1] =
 1  3  5  7   9
 2  4  6  8  10

[:, :, 2] =
 11  13  15  17  19
 12  14  16  18  20

[:, :, 3] =
 21  23  25  27  29
 22  24  26  28  30

julia> f(x::Matrix) = fill(x[1,1], 1,4);  # возвращает матрицу 1×4

julia> B = mapslices(f, A, dims=(1,2))
1×4×3 Array{Int64, 3}:
[:, :, 1] =
 1  1  1  1

[:, :, 2] =
 11  11  11  11

[:, :, 3] =
 21  21  21  21

julia> f2(x::AbstractMatrix) = fill(x[1,1], 1,4);

julia> B == stack(f2, eachslice(A, dims=3))
true

julia> g(x) = x[begin] // x[end-1];  # возвращает число

julia> mapslices(g, A, dims=[1,3])
1×5×1 Array{Rational{Int64}, 3}:
[:, :, 1] =
 1//21  3//23  1//5  7//27  9//29

julia> map(g, eachslice(A, dims=2))
5-element Vector{Rational{Int64}}:
 1//21
 3//23
 1//5
 7//27
 9//29

julia> mapslices(sum, A; dims=(1,3)) == sum(A; dims=(1,3))
true

Обратите внимание, что в eachslice(A; dims=2) указанное измерение не имеет двоеточия в срезе. Это view(A,:,i,:), тогда как mapslices(f, A; dims=(1,3)) использует A[:,i,:]. Функция f может изменять значения в срезе, не затрагивая A.

eachrow(A::AbstractVecOrMat) <: AbstractVector

Создает объект RowSlices, который является вектором строк матрицы или вектора A. Срезы строк возвращаются в виде представлений AbstractVector A.

Обратное действие см. в описании stack(rows; dims=1).

См. также описание eachcol, eachslice и mapslices.

Совместимость: Julia 1.1

Для этой функции требуется версия Julia не ниже 1.1.

Совместимость: Julia 1.9

До версии Julia 1.9 при этом возвращался итератор.

Примеры

julia> a = [1 2; 3 4]
2×2 Matrix{Int64}:
 1  2
 3  4

julia> s = eachrow(a)
2-element RowSlices{Matrix{Int64}, Tuple{Base.OneTo{Int64}}, SubArray{Int64, 1, Matrix{Int64}, Tuple{Int64, Base.Slice{Base.OneTo{Int64}}}, true}}:
 [1, 2]
 [3, 4]

julia> s[1]
2-element view(::Matrix{Int64}, 1, :) with eltype Int64:
 1
 2
eachcol(A::AbstractVecOrMat) <: AbstractVector

Создает объект ColumnSlices, который является вектором столбцов матрицы или вектора A. Срезы столбцов возвращаются в виде представлений AbstractVector A.

Обратное действие см. в описании stack(cols) или reduce(``hcat, cols).

См. также описание eachrow, eachslice и mapslices.

Совместимость: Julia 1.1

Для этой функции требуется версия Julia не ниже 1.1.

Совместимость: Julia 1.9

До версии Julia 1.9 при этом возвращался итератор.

Примеры

julia> a = [1 2; 3 4]
2×2 Matrix{Int64}:
 1  2
 3  4

julia> s = eachcol(a)
2-element ColumnSlices{Matrix{Int64}, Tuple{Base.OneTo{Int64}}, SubArray{Int64, 1, Matrix{Int64}, Tuple{Base.Slice{Base.OneTo{Int64}}, Int64}, true}}:
 [1, 3]
 [2, 4]

julia> s[1]
2-element view(::Matrix{Int64}, :, 1) with eltype Int64:
 1
 3
eachslice(A::AbstractArray; dims, drop=true)

Создает объект Slices, который является массивом срезов в измерениях dims объекта A, возвращая представления, которые выбирают все данные из других измерений в A. dims может быть целым числом или кортежем целых чисел.

Если drop = true (по умолчанию), внешние срезы Slices будут отбрасывать внутренние размеры, а порядок измерений будет соответствовать порядку в dims. Если drop = false, срезы (Slices) будет иметь ту же размерность, что и базовый массив, а размер внутренних измерений будет равен 1.

Обратное действие eachslice(A; dims::Integer) см. в описании stack(slices; dims).

См. также описание eachrow, eachcol, mapslices и selectdim.

Совместимость: Julia 1.1

Для этой функции требуется версия Julia не ниже 1.1.

Совместимость: Julia 1.9

До версии Julia 1.9 при этом возвращался итератор и в dims поддерживалось только одно измерение.

Примеры

julia> m = [1 2 3; 4 5 6; 7 8 9]
3×3 Matrix{Int64}:
 1  2  3
 4  5  6
 7  8  9

julia> s = eachslice(m, dims=1)
3-element RowSlices{Matrix{Int64}, Tuple{Base.OneTo{Int64}}, SubArray{Int64, 1, Matrix{Int64}, Tuple{Int64, Base.Slice{Base.OneTo{Int64}}}, true}}:
 [1, 2, 3]
 [4, 5, 6]
 [7, 8, 9]

julia> s[1]
3-element view(::Matrix{Int64}, 1, :) with eltype Int64:
 1
 2
 3

julia> eachslice(m, dims=1, drop=false)
3×1 Slices{Matrix{Int64}, Tuple{Int64, Colon}, Tuple{Base.OneTo{Int64}, Base.OneTo{Int64}}, SubArray{Int64, 1, Matrix{Int64}, Tuple{Int64, Base.Slice{Base.OneTo{Int64}}}, true}, 2}:
 [1, 2, 3]
 [4, 5, 6]
 [7, 8, 9]

Комбинаторика

invperm(v)

Возвращает обратную перестановку v. Если B = A[v], то A == B[invperm(v)].

См. также описание sortperm, invpermute!, isperm и permutedims.

Примеры

julia> p = (2, 3, 1);

julia> invperm(p)
(3, 1, 2)

julia> v = [2; 4; 3; 1];

julia> invperm(v)
4-element Vector{Int64}:
 4
 1
 3
 2

julia> A = ['a','b','c','d'];

julia> B = A[v]
4-element Vector{Char}:
 'b': ASCII/Unicode U+0062 (category Ll: Letter, lowercase)
 'd': ASCII/Unicode U+0064 (category Ll: Letter, lowercase)
 'c': ASCII/Unicode U+0063 (category Ll: Letter, lowercase)
 'a': ASCII/Unicode U+0061 (category Ll: Letter, lowercase)

julia> B[invperm(v)]
4-element Vector{Char}:
 'a': ASCII/Unicode U+0061 (category Ll: Letter, lowercase)
 'b': ASCII/Unicode U+0062 (category Ll: Letter, lowercase)
 'c': ASCII/Unicode U+0063 (category Ll: Letter, lowercase)
 'd': ASCII/Unicode U+0064 (category Ll: Letter, lowercase)
isperm(v) -> Bool

Возвращает true, если v является допустимой перестановкой.

Примеры

julia> isperm([1; 2])
true

julia> isperm([1; 3])
false
permute!(v, p)

Перестанавливает вектор v на месте в соответствии с перестановкой p. Проверка того, что p является перестановкой, не выполняется.

Для возвращения новой перестановки используйте v[p]. Как правило, выполняется быстрее, чем permute!(v, p); еще быстрее результат будет получен при записи данных в предварительно выделенный выходной массив с помощью u .= @view v[p]. (Хотя permute! перезаписывает v на месте, для отслеживания того, какие элементы были перемещены, требуется внутреннее выделение памяти.)

Если какой-либо измененный аргумент размещается в одной области памяти с любым другим аргументом, поведение может быть непредвиденным.

См. также описание invpermute!.

Примеры

julia> A = [1, 1, 3, 4];

julia> perm = [2, 4, 3, 1];

julia> permute!(A, perm);

julia> A
4-element Vector{Int64}:
 1
 4
 3
 1
invpermute!(v, p)

Аналогично permute!, но применяется перестановка, обратная заданной.

Обратите внимание, что для предварительно выделенного выходного массива (например, u = similar(v)) быстрее будет использовать u[p] = v. (invpermute! автоматически выделяет память для копии данных.)

Если какой-либо измененный аргумент размещается в одной области памяти с любым другим аргументом, поведение может быть непредвиденным.

Примеры

julia> A = [1, 1, 3, 4];

julia> perm = [2, 4, 3, 1];

julia> invpermute!(A, perm);

julia> A
4-element Vector{Int64}:
 4
 1
 3
 1
reverse(A; dims=:)

Выполняет реверсирование A в измерении dims, которое может быть целочисленным значением (одно измерение), кортежем целочисленных значений (кортеж измерений) или : (реверсирование во всех измерениях, используется по умолчанию). См. также описание reverse! для реверсирования на месте.

Примеры

julia> b = Int64[1 2; 3 4]
2×2 Matrix{Int64}:
 1  2
 3  4

julia> reverse(b, dims=2)
2×2 Matrix{Int64}:
 2  1
 4  3

julia> reverse(b)
2×2 Matrix{Int64}:
 4  3
 2  1
Совместимость: Julia 1.6

До Julia 1.6 в reverse поддерживались только одинарные целочисленные dims.

reverseind(v, i)

С учетом индекса i в reverse(v) возвращает соответствующий индекс в v так, чтобы v[reverseind(v,i)] == reverse(v)[i]. (Это может быть нетривиальным в случаях, когда v содержит не символы ASCII.)

Примеры

julia> s = "Julia🚀"
"Julia🚀"

julia> r = reverse(s)
"🚀ailuJ"

julia> for i in eachindex(s)
           print(r[reverseind(r, i)])
       end
Julia🚀
reverse!(v [, start=firstindex(v) [, stop=lastindex(v) ]]) -> v

Версия reverse, выполняемая на месте.

Примеры

julia> A = Vector(1:5)
5-element Vector{Int64}:
 1
 2
 3
 4
 5

julia> reverse!(A);

julia> A
5-element Vector{Int64}:
 5
 4
 3
 2
 1

reverse!(A; dims=:)

Аналогично reverse, но работает на месте в A.

Совместимость: Julia 1.6

Для многомерной функции reverse! требуется версия Julia не ниже 1.6.