Matrices and Matrix Operations
Creating matrices
A matrix is a rectangular numeric table or two-dimensional array. It consists of rows and columns (the size is written as ). Matrices are usually denoted by uppercase Latin letters, and their elements are lowercase with a double index: , where is the row number and is the column number.
Call np.array()
to create a numpy
matrix from a list of lists. All nested lists are the same length.
1import numpy as np23matrix = np.array([4 [1, 2, 3],5 [4, 5, 6],6 [7, 8, 9]])7print(matrix)
Let's take a list of vectors instead of a list of lists:
1import numpy as np23string0 = np.array([1,2,3])4string1 = np.array([-1,-2,-3])5list_of_vectors = [string0, string1]6matrix_from_vectors = np.array(list_of_vectors)78print(matrix_from_vectors)
Create a matrix from the pandas table: its values
attribute is a matrix.
1import pandas as pd2import numpy as np34matrix = df.values5print(matrix)
The shape
attribute defines the size of the matrix . Its element is set in numpy
as A[i,j]
: rows and columns are numbered from zero, just like array indices.
1import numpy as np23A = np.array([4 [1, 2, 3],5 [2, 3, 4]])67print('Size:', A.shape)8print('A[1, 2]:', A[1, 2])
Select individual rows and columns from the matrix:
1import numpy as np23matrix = np.array([4 [1, 2, 3],5 [4, 5, 6],6 [7, 8, 9],7 [10,11,12]])89print('Row 0:', matrix[0, :])10print('Column 2:', matrix[:, 2])
Operations with matrix elements
You can do the same operations with matrix elements as you do with vector elements. Two matrices can be added, subtracted, multiplied, or divided. The most important part is that the operations are performed element-by-element, and the matrices are the same size. The result of an operation is a matrix of the same size.
1import numpy as np23matrix1 = np.array([4 [1, 2],5 [3, 4]])67matrix2 = np.array([8 [5, 6],9 [7, 8]])1011print(matrix1 + matrix2)
You can multiply a matrix by a number, add a number, or subtract it: the operation is applied to each element.
1import numpy as np23matrix = np.array([4 [1, 2],5 [3, 4]])67print(matrix * 2)8print(matrix - 2)
Multiplying a matrix by a vector
Each row of this list (matrix) is a vector multiplied by a scalar, and the resulting numbers form a new vector.
For example, a matrix with the size is multiplied by a vector (-dimensional). The product will be a new vector . This is a -dimensional vector whose coordinate is equal to the scalar product of row of the matrix and .
Let's perform this operation in numpy
and call the familiar to us the np.dot()
function.
1import numpy as np23A = np.array([4 [1, 2, 3],5 [4, 5, 6]])67b = np.array([7, 8, 9])89print(np.dot(A, b))10print(A.dot(b))
For multiplication to be correct, the size of the vector must be equal to the width of the matrix.
Transpose of matrix
The transpose of a matrix is its "flip" over the main diagonal of the matrix, which goes from the upper-left to the lower-right corner.
With this reversal, the matrix of the size is transformed into a matrix of the size. In other words, the rows of the matrix become its columns, and the columns become its rows.
The transposed matrix is indicated by the upper index T
.
In NumPy, this operation is set by the T
attribute. If you need to build a matrix, start from the list of columns to create a matrix and apply transpose:
1import numpy as np23matrix = np.array([4 [1, 2],5 [4, -4],6 [0, 17]])78print("Transposed matrix")9print(matrix.T)
Multiply the original matrix by a vector with the length equal to 3:
1vector = [2, 1, -1]2print(np.dot(matrix, vector))
We got an error: the dimensions of the matrix (3, 2) and the vector (3,) are not aligned. The second dimension of the matrix is not equal to the length of the vector. To make the multiplication correct, we transpose the matrix:
1print(np.dot(matrix.T, vector))
Matrix multiplication
During Matrix multiplication, a third matrix is constructed using two matrices. It consists of scalar products of the rows of the first matrix by the columns of the second. The product of the row of the matrix () and the column of the matrix () is equal to the matrix :
Matrix multiplication is possible if the width of the first matrix () is equal to the height of the second matrix (). Then the dimensions of their product will be . We say that the dimension n "collapses".
In numpy
, matrices and are multiplied by calling the functions np.dot(A, B)
, or A.dot(B)
. You can also replace this call with a matrix multiplication sign @
.
1import numpy as np23print(A.dot(B))4print(np.dot(A,B))5print(A @ B)
The result of matrix multiplication depends on the order of multipliers. The result of matrix multiplication depends on the order of multipliers.
1matrix = np.array([2 [1, 2, 3],3 [-1, -2, -3]])45print(matrix @ matrix)
An error occurred: the dimensions of the matrices are mismatched.
Multiplying the matrix by itself is only possible if it is square:
1square_matrix = np.array([2 [1, 2, 3],3 [-1, -2, -3],4 [0, 0, 0]])56print(square_matrix @ square_matrix)