Basic operations with matrices¶
A matrix is a two-dimensional rectangular array of elements arranged in rows and columns. Elements can be numbers, logical values (true or false), date and time, strings, categorical values or some other type of data.
Matrix definition¶
A matrix can be created using square brackets [] by enclosing the required elements in them in advance.
Pkg.add(["LinearAlgebra"])
A = [1 2 3] # создание матрицы в виде вектор-строки
A matrix with one column will be displayed as another data type - vector:
A = [1, 2, 3]
Creating a regular, rectangular matrix is done by defining rows and separating them with a semicolon sign:
A = [1 2 3 4; 5 6 7 8]
There are many functions that help you create matrices with specific element values or a specific structure. For example, the functions zeros and ones create matrices of all zeros or ones. The first and second arguments of these functions are the number of rows and the number of columns of the matrix:
A = zeros(3, 3) # определение матрицы с нулями
A = ones(3, 3) # определение матрицы с единицами
The function Diagonal, of the LinearAlgebra library places the input elements on the diagonal of an array:
using LinearAlgebra
A = [12, 62, 93, -8]
B = Diagonal(A)
Use the convert function to convert matrix B from the Diagonal type to the Matrix{Float64} data type
B = convert(Matrix{Float64}, B)
Matrix union¶
Matrices can be combined horizontally using square brackets [ ]:
A = [1 2; 3 4; 5 6; 7 8]
C = [A B]
Similarly, matrices can be combined vertically (must be of the same dimension) by specifying a semicolon:
A = ones(1,4)
B = zeros(1,4)
D = [A; B]
Special functions such as vcat and hcat can be used to merge:
C = hcat(A, B)
D = vcat(A, B)
Generating numerical sequences¶
With the collect function you can generate a numeric sequence as a vector:
E = collect(-10:5:10) # collect(Начало:Интервал:Конец)
Changing the shape of a matrix¶
In order to change the dimension of the matrix you can use the reshape function.
A = [1 2 3 4 5; 6 7 8 9 10; 11 12 13 14 15; 16 17 18 19 20] # определяем матрицу, исходный размер 4 на 5
Convert the matrix into a vector-string:
reshape(A, (1, 20))
Convert the matrix to a vector-column:
reshape(A, (20, 1))
If you specify one of the matrix dimensions with a colon, reshape will return a matrix with the specified number of rows or columns:
reshape(A, (1, :))