Arrays, vectors and matrices in Engee
Introduction
Arrays, vectors and matrices are used in Engee to handle data, parameters and complex structures. These structures, implemented in the language Julia, allow efficient storage and processing of numerical information, including computational results, signals, and parameters of models. This paper discusses the features of each of them.
In Julia, the numbering of elements of arrays, vectors, and matrices begins with 1 rather than 0 as in some other languages. The last element has the index end . This is in keeping with the mathematical tradition, where indexing also starts with one. For example, the first element of the array a = [1, 2, 3] is accessed by a[1] , and the last element by a[end] . See below for more details.
|
An array is a generalised multidimensional container that can contain elements of any type. Arrays in Julia support any number of dimensions, making them a versatile tool for storing and manipulating data:
A = rand(2, 2, 3)
Output
2×2×3 Array{Float64, 3}:
[:, :, 1] =
0.159525 0.787948
0.358068 0.124023
[:, :, 2] =
0.228296 0.292929
0.712896 0.0253828
[:, :, 3] =
0.3547 0.837655
0.474441 0.201402
Arrays are dynamic and static:
-
Dynamic arrays are arrays whose size can change during programme execution. They are stored in memory with an eye to possible expansion, making them more flexible but less optimal for computationally intensive tasks. Example:
dynamic_array = [1, 2, 3] dynamic_array[2] = 5 # Присваивание значения push!(dynamic_array, 4) # Добавление элемента deleteat!(dynamic_array, 3) # Удаление элемента с индексом 3
Output
4-element Vector{Int64}: 1 5 3 4
-
Static arrays are arrays of a fixed size that is set at the creation stage. They are stored in memory as a continuous block of data, which allows operations to be performed faster by minimising memory management overhead.
Static arrays are efficient when their size is smaller than 100-200 elements. If the size is larger than 100-200 elements, dynamic arrays are usually used. In Julia, static arrays are provided by the StaticArrays.jl package. Therefore, to use them, you must connect this package using the
using StaticArrays
command. Example:using StaticArrays static_array = @SVector [1, 2, 3]
Output
3-element SVector{3, Int64} with indices SOneTo(3): 1 2 3
The code used a macro[1]
@SVector
, which creates a static one-dimensional array (vector) of fixed size. There are other useful macros for static arrays:Static Array Macros.
-
@SVector
- creates an immutable static vector of fixed size. Example:@SVector [1, 2, 3]
. -
@MVector
- creates a mutable static vector of fixed size. Example:@MVector [1, 2, 3]
. -
@SMatrix
- creates a mutable static matrix of fixed size. Example:@SMatrix [1 2; 3 4]
. -
@MMatrix
- creates a mutable static matrix of fixed size. Example:@MMatrix [1 2; 3 4]
. -
@SizedArray
- converts a regular array into a static array with a fixed size. Example:@SisedArray rand(2, 2)
. -
@SArray
- creates a common fixed-size static array, which can be a vector, matrix, or a higher dimensional array. Example:@SArray rand(2, 2, 2, 2)
. -
@MArray
- creates a common mutable static array. Example:@MArray rand(2, 2, 2, 2)
. -
@StaticArray
- a generic macro that creates immutable arrays of any shape. Example:@StaticArray rand(2, 2, 2)
. -
@MutableStaticArray
is a universal macro for creating mutable static arrays. Example:@MutableStaticArray rand(2, 2)
. -
@zeros
- creates a static array filled with zeros. Example:@zeros(SVector, 3)
creates a vector of three zeros. -
@ones
- creates a static array filled with ones. Example:@ones(SMatrix, 2, 2)
creates a 2×2 matrix of ones. -
@fill
- creates a static array filled with the given value. Example:@fill(SVector, 3, 42)
creates a vector of three elements with the value 42. -
@static
- optimises the execution of code blocks at the compilation stage by applying the properties of static arrays. Example:@static if length(SVector(1, 2, 3)) == 3 println("Размер вектора равен 3") end
-
Unlike C++, arrays in Julia can store elements of different types. If element types can be reduced to a common type (e.g.
If the element types cannot be reduced to a common type (e.g. number and string), Julia will cast the array to type
This makes arrays in Julia flexible, but it is worth remembering that usage of |
A Vector is a one-dimensional array that is a sequence of elements accessed using indices. In Julia, a vector can be created as a vector-column or vector-string, but their syntax and data type will be different:
-
A column vector is created by usage of commas or column entries:
v = [1, 2, 3] # Вектор-столбец
or
v = [1 2 3] # Вектор-столбец
Output
3-element Vector{Int64}: 1 2 3
-
Julia does not have a separate type for a vector string. Instead, a string of numbers is represented as a matrix of dimension 1 × N:
r = [1 2 3] # Матрица 1 × 3
Output
1×3 Matrix{Int64}: 1 2 3
In Julia, delimiters in arrays define their structure:
|
A Matrix is a two-dimensional array representing a table of numbers or other objects organised into rows and columns. In Julia, matrices are created as arrays with two dimensions:
M = [1 2 3; 4 5 6]
Output
2×3 Matrix{Int64}:
1 2 3
4 5 6
The separation into vectors and matrices in Julia allows for efficient organisation of data in memory, which is important for fast numerical calculations. Vectors use one-dimensional storage, making it easier to work with sequences of data, while matrices are organised in two-dimensional form, making it easier to perform linear algebra (multiplication and transpose). This separation helps optimise usage of cache memory and CPU resources, making computations more productive.
Differences between arrays, vectors and matrices
Dimensionality:
-
An array is a container with an arbitrary number of dimensions. Arrays have an arbitrary number of dimensions, and
size(A)
can return, for example, (2
,2
,3
). -
A vector is a one-dimensional array. Vectors always have one dimension, and the function
size(v)
returns the tuple(n,)
, wheren
is the length of the vector. -
A matrix is a two-dimensional array. Matrices have a dimensionality of two, and
size(M)
returns the tuple(n, m)
, wheren
is the number of rows andm
is the number of columns.
A tuple is an immutable data structure that can contain multiple elements of different types. In Julia, tuples are used to represent values that are logically related but do not require modification. For example, the result of the Unlike a vector and a matrix, a tuple is not an array and is not designed to perform arithmetic operations. It has a fixed number of elements and an immutable structure, making it useful for returning multiple values from functions or passing parameters. |
-
Implementation Features:
-
Methods and functions for working with arrays are applicable to both vectors and matrices. However, there are different optimised algorithms for each type of data.
-
In Julia, vectors and matrices are special cases of arrays, where a vector has dimension
1
and a matrix has dimension2
.
-
-
Initialisation and syntax:
-
An array with arbitrary dimensionality is created by the Array function or by using generators (expressions in the form
[… for …]
). For example, for Array:A = Array{Float64}(undef, 2, 2, 3)
Here undef is a keyword used to create an array without initialising the elements. This means that memory for the array will be allocated, but the values of its elements will remain undefined (may be random).
Example with generators:
array = [i^2 for i in 1:5] # Каждый элемент массива – квадрат числа от 1 до 5
-
A vector is created as a one-dimensional array, elements are enumerated using commas:
v = [1, 2, 3]
-
A matrix is written as semicolon-separated rows (
;
), and the elements in the rows are separated by spaces or tabs:M = [1 2 3; 4 5 6]
-
-
Memory storage:
-
Arrays with a large number of dimensions use a more general storage approach, which can increase the overhead of operations.
-
The differences described above form specific application areas:
-
Array is used for modelling more complex data: three-dimensional models, image arrays or multidimensional time series.
-
A vector is most often used for one-dimensional data: time series, coordinates, signals.
-
A matrix represents two-dimensional structures: images, tables, systems of linear equations.
Basic functions for working with arrays, vectors and matrices
Julia provides a wide set of functions for working with arrays, including vectors and matrices. Read more about the functions and their signatures in Arrays.
Functions marked with
The |
Below is a list of basic functions with brief descriptions and examples:
Creation
Function name |
Description |
Example |
|
Creates an array whose elements are equal to zero. The type of the created object depends on the passed arguments: one-dimensional array (vector), two-dimensional array (matrix) or multidimensional array. |
[source,julia]. zeros(3) zeros(2, 2) zeros(2, 2, 3) here:
|
|
Creates an array whose elements are equal to one. The type of the created object depends on the passed arguments: one-dimensional array (vector), two-dimensional array (matrix) or multidimensional array. |
[source,julia]. ones(3) ones(2, 2) ones(2, 2, 3) here:
|
|
Creates an array filled with random numbers with uniform distribution in the interval |
[source,julia]. rand(3) rand(2, 2) rand(2, 2, 3) here:
|
|
Creates an array filled with the specified value. The type of the created object depends on the passed arguments: one-dimensional array (vector), two-dimensional array (matrix) or multidimensional array. |
[source,julia]. fill(7, 3) fill(5, 2, 2) fill(75, 2, 2, 3) here:
|
|
Creates an array by converting the given range or iterated object. The type of object created depends on the input used. |
[source,julia]. collect(1:3) collect(reshape(1:4, 2, 2)) collect(reshape(1:12, 2, 2, 3)) Here:
|
Change of structure
Function name |
Description |
Example |
|
Adds an element to the end of a one-dimensional array (vector). Applies only to modifiable (dynamic) arrays. The end index can also be used to add an element (Array indexing). |
[source,julia]. v = [1, 2, 3] push!(v, 4) m = reshape(1:6, 2, 3) # push! нельзя применить к матрице или многомерному массиву. here:
|
|
Deletes and returns the last element from a one-dimensional array (vector). Applies only to modifiable (dynamic) arrays. |
[source,julia]. v = [1, 2, 3, 4] last_element = pop!(v) m = reshape(1:6, 2, 3) # pop! нельзя применить к матрице или многомерному массиву. here:
|
|
Inserts an element at the specified position of a one-dimensional array (vector). Applies only to modifiable (dynamic) arrays. |
[source,julia]. v = [1, 2, 4, 5] insert!(v, 3, 3) m = reshape(1:6, 2, 3) # insert! нельзя применить к матрице или многомерному массиву. here:
|
|
Deletes an element at the specified index from a one-dimensional array (vector). Applies only to modifiable (dynamic) arrays. |
[source,julia]. v = [1, 2, 3, 4, 5] deleteat!(v, 3) m = reshape(1:6, 2, 3) # deleteat! нельзя применить к матрице или многомерному массиву. here:
|
Working with dimensions
Function name |
Description |
Example |
|
Returns the size of an array, matrix or vector as a tuple, where each value corresponds to a size on a particular dimension. |
[source,julia]. v = [1, 2, 3] size(v) m = reshape(1:6, 2, 3) size(m) a = zeros(2, 2, 3) size(a) Here:
|
|
Changes the size of a one-dimensional array (vector). If the new size is larger than the current size, the new elements are initialised with the default value |
[source,julia]. v = [1, 2, 3] resize!(v, 5) resize!(v, 2) m = reshape(1:6, 2, 3) # resize! нельзя применить к матрице или многомерному массиву. Here:
|
|
Returns the total number of elements in an array, vector or matrix, regardless of their dimensionality. |
[source,julia]. v = [1, 2, 3] length(v) m = reshape(1:6, 2, 3) length(m) a = zeros(2, 2, 3) length(a) here:
|
|
Returns the number of dimensions (dimensions) of an array, vector or matrix. |
[source,julia]. v = [1, 2, 3] ndims(v) m = reshape(1:6, 2, 3) ndims(m) a = zeros(2, 2, 3) ndims(a) here:
|
|
Changes the dimensionality of an array, matrix or vector, converting it to a new array with the specified number of rows and columns. The number of elements in the new array must match the number of elements in the original array. |
here:
|
Linear Algebra
Function name |
Description |
Example |
|
Returns a transposed array or matrix where the rows swap places with the columns. For a one-dimensional array (vector), the result depends on its orientation. |
[source,julia]. v = [1, 2, 3] vt = transpose(v) m = [1 2; 3 4; 5 6] mt = transpose(m) Here:
|
* |
Calculates the determinant of a square matrix. It is a part of LinearAlgebra package (requires package installation). The determinant is a scalar quantity that characterises the properties of a matrix (e.g. its reversibility). |
here:
|
|
Computes the inverse matrix for a square matrix. The inverse matrix exists only for matrices with non-zero determinant, that is, for those that are reversible. The |
[source,julia]. m1 = [2 3; 1 4] inv(m1) m2 = [1 2 3; 0 1 4; 5 6 0] inv(m2) m3 = [1 2; 3 4] inv(m3) Here:
|
* |
Calculation of eigenvalues and vectors of a matrix. For example:
|
[source,julia]. m1 = [4 1; 2 3] eigvals(m1) eigvecs(m1) m2 = [1 2 3; 4 5 6; 7 8 9] eigvals(m2) eigvecs(m2) here:
|
|
Calculates the norm of a vector or matrix. The norm is a numerical characteristic that measures the "size" of a vector or matrix. By default, the Euclidean norm is calculated. |
here:
|
Check.
Function name |
Description |
Example |
|
Checks if an array, vector or matrix is empty. Returns |
Here:
|
|
Checks whether the object is null. Returns Supports numeric types as well as arrays, matrices and vectors (in Julia, an object is null if all its elements are zero). |
[source,julia]. # Проверка числа x = 0 y = 5 iszero(x) # true iszero(y) # false # Проверка вектора v1 = [0, 0, 0] v2 = [0, 1, 0] iszero(v1) # true iszero(v2) # false # Проверка матрицы m1 = zeros(2, 2)нулями m2 = [1 0; 0 0]элементом iszero(m1) # true iszero(m2) # false # Проверка многомерного массива a1 = zeros(2, 2, 2) a2 = reshape([1, 0, 0], 1, 3) iszero(a1) # true iszero(a2) # false here: For numbers:
For vectors:
For matrices:
For multidimensional arrays:
|
|
Checks whether the matrix is symmetric. Returns |
[source,julia]. # Симметричная матрица m1 = [1 2 3; 2 4 5; 3 5 6] issymmetric(m1) # true # Несимметричная матрица m2 = [1 0 0; 0 4 5; 3 5 6] issymmetric(m2) # false # Квадратная, но несимметричная матрица m3 = [1 2; 3 4] issymmetric(m3) # false # Несимметричная прямоугольная матрица m4 = [1 2; 2 3; 3 4] issymmetric(m4) # false Here:
|
Transformation.
Function name |
Description |
Example |
|
Converts a matrix or multidimensional array to a vector. It returns a one-dimensional array in which the elements are taken from the columns of the original matrix or array. If the argument is already a vector, it returns unchanged. |
[source,julia]. # Преобразование матрицы в вектор m = [1 2; 3 4] v1 = vec(m) # [1, 3, 2, 4] # Преобразование трехмерного массива в вектор a = zeros(2, 2, 2) a[:, :, 1] .= [1 2; 3 4] a[:, :, 2] .= [5 6; 7 8] v2 = vec(a) # [1, 3, 2, 4, 5, 7, 6, 8] # Преобразование вектора (без изменений) v = [1, 2, 3] v3 = vec(v) # [1, 2, 3]
|
|
Rearrangement of measurements (axes) of a multidimensional array. Allows you to change the order of measurements without changing the data itself, creating a new array with rearranged axes. |
here:
|
|
Horizontal and vertical joining of arrays (Concatenation).
|
[source,julia]. # Горизонтальное объединение (hcat) v1 = [1, 2, 3] v2 = [4, 5, 6] h_result = hcat(v1, v2) # Вертикальное объединение (vcat) v3 = [7, 8, 9] v_result = vcat(v1, v3) # Объединение матриц m1 = [1 2; 3 4] m2 = [5 6; 7 8] hcat_result = hcat(m1, m2) vcat_result = vcat(m1, m2) here:
|
|
creates an independent copy of an array, vector or matrix. Changes made to the copy do not affect the original object and vice versa. |
[source,julia]. v = [1, 2, 3] v_copy = copy(v) v[1] = 10 # Изменяем оригинал println(v) # [10, 2, 3] println(v_copy) # [1, 2, 3] Here:
|
|
creates a deep copy of the array, recursively copying all nested structures. Changes to the copy do not affect the original. In Julia, the assignment by default passes an object reference rather than a value. If you need to create an independent copy, there are two ways:
|
[source,julia]. A = [[1, 2], [3, 4]] B = copy(A) # Неглубокая копия C = deepcopy(A) # Глубокая копия B[1][1] = 99 println(A) # [[99, 2], [3, 4]] — A изменился, потому что B и A связаны println(C) # [[1, 2], [3, 4]] — Глубокая копия не изменилась here:
|
|
Allows operations on array elements with automatic size matching (broadcasting). For more details see. here. |
[source,julia]. # Пример с вектором v = [1, 2, 3] v_squared = broadcast(x -> x^2, v) # Пример с матрицей m = [1 2; 3 4] m_doubled = broadcast(x -> x * 2, m) # Пример с разными размерами массивов a = [1, 2, 3] b = [4, 5] result = broadcast(+, a, b') here:
|
Appropriateness of using arrays
Arrays are a convenient and flexible tool for working with data, but Julia has other structures that may be better suited for certain tasks. See below for more details.
When arrays are recommended
-
Fast access to elements by index - arrays store elements sequentially in memory, allowing instant access to any element by its index. For example,
arr[3]
will immediately return the third element of the array. This is called random access (random access), and it runs inO(1)
time (the operation takes a constant amount of time regardless of the size of the input data, i.e. accessing an element by index takes the same amount of time no matter how large the array is). -
Efficient add and remove at the end - if you need to frequently add or remove elements at the end of an array, then use the
push!
(add an element) andpop!
(remove the last element) functions. These operations are very fast because they do not require rearranging other elements. -
Working with a fixed amount of data - If you know in advance how many elements will be stored, arrays work particularly efficiently. They allocate memory all at once, which minimises resizing overhead.
-
Vector Computing and Linear Algebra - Julia is optimised for working with arrays, especially numeric arrays. If you work with matrices, vectors, or perform linear algebra operations, arrays are the best choice. For example, functions for working with matrices, such as
dot
,cross
, or array operations via broadcast (.+
,.*
), work faster with arrays.
When arrays are not recommended
-
Frequent addition or deletion of elements in the middle or beginning - if you need to frequently insert or delete elements in the beginning or middle of an array. For example, the
insert!
(insert) anddeleteat!
(delete) functions require shifting all subsequent elements, making them inefficient for large arrays. Alternative: useDeque
from theDataStructures.jl
package, which is optimised for insertion and deletion at both ends. -
Find items by key - if you need to quickly find items by unique keys (e.g. user name or ID), arrays are not suitable, because they are searched by searching all items (which is quite time-consuming). Alternative: use
Dict
(dictionary), which allows you to quickly find items by key. -
Frequent resizing of the structure - if the structure of the data changes frequently (e.g. elements are added or removed at arbitrary locations), arrays will be ineffective. Alternative: consider usage of
Set
,Dict
or list structures such asList
from the link:https://juliacollections.github.io/DataStructures.jl/latest/ package [DataStructures.jl]. -
Working with immutable data - arrays in Julia are mutable, meaning their elements can be changed after they are created. If you need an immutable data structure, it is better to use tuples (Tuple). They do not allow you to change their elements, which makes them convenient for storing constant data. For example:
t = (1, 2, 3) t[1] = 10 # Ошибка! Кортежи неизменяемы
Arrays, matrices and vectors of strings and symbols
In Julia, arrays, matrices, and vectors can contain strings or symbols, just like numbers.
# Вектор строк
v = ["apple", "banana", "cherry"]
println(v[1]) # apple
# Матрица символов
m = ['a' 'b'; 'c' 'd']
println(m[1, 2]) # b
# Трехмерный массив строк
a = [["a", "b"], ["c", "d"]]
println(a[1][2]) # "b"
-
String vector - each string is stored as an element of a one-dimensional array.
-
Character matrix - a two-dimensional array where each element is a character.
-
Three-dimensional array of strings - any number of dimensions with text data is supported.
Arrays in Julia are dynamic by default, but their length is fixed until explicitly changed. This means that when an array is created, its current length remains unchanged until special methods such as push!
, append!
, or resize!
are used. This is done to improve performance: fixed-length operations are faster because they do not require constant memory reallocation.
More complex constructs with end
, such as end+1
, do not allow you to directly assign a value to an array element, because such operations go beyond the current length. To add new elements, you must explicitly increase the size of the array. For example, you can use resize!
:
a = [10, 20, 30]
resize!(a, length(a) + 1) # Расширяем массив на 1 элемент
a[end] = 40 # Присваиваем значение новому элементу
println(a) # [10, 20, 30, 40]
Constructions with end
are available for indexing and performing arithmetic operations on indexes inside existing array boundaries. For example:
-
a[end]
- access to the last element. -
a[end-1]
- access to the second element from the end. -
a[1:end]
- get the whole array. -
a[1:end-1]
- get all elements except the last one.
In Julia you cannot directly assign a value to an element with index end+1 or any index beyond the current length of the array. To resize an array, you must use special methods such as resize! , push! , or append! .
|
Array indexing
Indexing in Julia starts from one, i.e. the first element of an array has index 1
. A special end
index is also supported, which denotes the last element of the array or the size of the corresponding dimension. Indexing example:
a = [10, 20, 30, 40]
println(a[1]) # 10 — первый элемент
println(a[end]) # 40 — последний элемент
# Индексация матриц
m = [1 2; 3 4]
println(m[1, end]) # 2 — последний элемент первой строки
-
The index
1
always points to the first element. -
end
is used to refer to the last element in one-dimensional and multidimensional arrays. -
For matrices, the first index is the row number, the second index is the column number.
*Other indexing variations:
-
You can refer to multiple elements of an array at once by usage of ranges:
b = [1, 2, 3, 4, 5] println(b[2:end]) # [2, 3, 4, 5] — элементы со второго до последнего
-
Selecting elements in specific increments:
b = [1, 2, 3, 4, 5] println(b[1:2:end]) # [1, 3, 5] — элементы с шагом 2
In Julia, expressions of the form
1:2:end
are called ranges. A range is a structure that describes a sequence of numbers with a beginning, a step, and an end. For example,1:2:5
creates a sequence from 1 to 5 in increments of 2:[1, 3, 5]
.In this example,
1:2:end
indicates that the selection starts at the first element of the array (1
), proceeds in increments of2
, and ends at the last element of the array (end
). Ranges are used to work with array and matrix indices in a convenient and efficient manner. Examples of usage of ranges:# Простые диапазоны r1 = 1:5 # Создает последовательность [1, 2, 3, 4, 5] r2 = 1:2:10 # Создает последовательность [1, 3, 5, 7, 9] # Использование диапазона для индексации a = [10, 20, 30, 40, 50] println(a[2:4]) # [20, 30, 40] println(a[1:2:end]) # [10, 30, 50] # Диапазон с "end" println(a[3:end]) # [30, 40, 50]
-
Selecting items that fulfil certain conditions (see section for details). Logical indexing):
b = [1, 2, 3, 4, 5] println(b[b .> 3]) # [4, 5] — элементы больше 3
In Julia, ranges can be set not only directly, but also by usage of variables. For example:
arr = [10, 20, 30, 40, 50]
a = 1:2:5 # Задаем диапазон в переменной
println(arr[a]) # [10, 30, 50]
Logical indexing
Logical indexing in Julia allows you to select array elements based on conditions that return a logical array (true
/false
) of the same dimension as the original array. This method is useful for filtering data. Example:
# Исходный массив
a = [10, 20, 30, 40, 50]
# Условие: выбрать элементы больше 25
filtered = a[a .> 25] # [30, 40, 50]
println(filtered)
# Условие: элементы, которые кратны 10
filtered = a[a .% 10 .== 0] # [10, 20, 30, 40, 50]
println(filtered)
Here:
-
.
operator before a condition (.>
,.==
) means a piecewise operation. A more detailed description of such operations is given in the article Vectorisation and logical indexing. -
logical array
[false, false, true, true, true, true]
will be used to select the corresponding elements.
Example with a multidimensional array:
# Матрица 2x3
m = [1 2 3; 4 5 6]
# Условие: выбрать элементы больше 3
filtered = m[m .> 3] # [4, 5, 6]
println(filtered)
Operators for working with arrays, vectors and matrices
Julia provides operators to simplify working with arrays - whether they are one-dimensional (vectors), two-dimensional (matrices), or more complex multidimensional structures. Here are the main operators used for indexing, transforming, and combining data:
-
The
:
operator is used to select all elements of an array along a particular dimension or to create ranges. Example:# Исходный массив m = [1 2 3; 4 5 6; 7 8 9] # Все элементы первой строки println(m[1, :]) # [1, 2, 3] # Все элементы второго столбца println(m[:, 2]) # [2, 5, 8] # Диапазон индексов println(m[1:2, 1:2]) # [1 2; 4 5]
-
The
'
operator is used for conjugation (transpose for real numbers). It works only with numeric arrays. Example:# Вектор-строка v = [1 2 3] # Транспонирование в столбец println(v') # [1; 2; 3;;]
To transpose arrays with complex numbers, the '
operator also returns a complex-conjugate result. If you need only row-to-column transposition (without conjugation), use thetranspose
function.
To transpose arrays with non-numeric elements (such as strings or user-defined types), use the If you apply the
|
-
The
;
operator is used to merge arrays vertically, that is, to add rows. Example:# Исходные векторы a = [1, 2, 3] b = [4, 5, 6] # Вертикальная конкатенация result = [a; b] println(result) # 6-element Vector{Int64}:[1; 2; 3; 4; 5; 6]
Iterate over arrays using for
In Julia, arrays can be conveniently iterated over using the for
loop. Let’s look at the basic ways of working with arrays via for
. The following syntax is used to loop through all elements of an array:
arr = [10, 20, 30, 40]
for x in arr
println(x)
end
Output
10
20
30
40
Sometimes it is necessary to get not only values, but also their indexes. For this purpose, eachindex
is used, which automatically selects the optimal indexing method:
arr = ["a", "b", "c"]
for i in eachindex(arr)
println("Элемент ", i, ": ", arr[i])
end
Output
Элемент 1: a
Элемент 2: b
Элемент 3: c
An alternative way to get the index and value is the enumerate
function:
arr = ["apple", "banana", "cherry"]
for (i, val) in enumerate(arr)
println("$i: $val")
end
Output
1: apple
2: banana
3: cherry
For multidimensional arrays, you can use nested loops:
matrix = [1 2 3; 4 5 6]
for i in 1:size(matrix, 1) # Проход по строкам
for j in 1:size(matrix, 2) # Проход по столбцам
println("matrix[$i, $j] = ", matrix[i, j])
end
end
Output
matrix[1, 1] = 1
matrix[1, 2] = 2
matrix[1, 3] = 3
matrix[2, 1] = 4
matrix[2, 2] = 5
matrix[2, 3] = 6
Instead of nested loops, you can use for
directly:
matrix = [1 2 3; 4 5 6]
for x in matrix
println(x)
end
Output
1
4
2
5
3
6
Julia traverses elements by columns, not by rows. To bypass the array by rows, you can use permutedims
or eachrow
:
for row in eachrow(matrix)
println(row)
end
Output
[1, 2, 3]
[4, 5, 6]
@
symbol that transform code before it is executed.