Matrix
The Matrix
class is used to store a mathematical matrix. Each instance of Matrix
represents an \(n \times m\)
matrix that can be written as:
Creating a matrix
The Matrix
class provides four different constructors for creating a new Matrix
:
Create a new matrix and fill in the values:
LouLib::Matrix A1(2, 3);
A[0][0] = 1;
A[0][1] = 2;
A[0][2] = 3;
A[1][0] = 4;
A[1][1] = 5;
A[1][2] = 6;
Create a matrix from
std::initializer_list<std::initializer_list<double>>
:
LouLib::Matrix A2({{1, 2, 3}, {4, 5, 6}});
Create a matrix from
std::vector<std::vector<double>>
:
std::vector<double> row1;
row1.push_back(1);
row1.push_back(2);
row1.push_back(3);
std::vector<double> row2;
row2.push_back(4);
row2.push_back(5);
row2.push_back(6);
std::vector<std::vector<double>> matrixData;
matrixData.push_back(row1);
matrixData.push_back(row2);
LouLib::Matrix A3(matrixData);
Create a copy of an already existing matrix:
LouLib::Matrix A4(A1);
All four of the examples above create the same matrix:
Accessing elements in a matrix
The elements of a matrix can be accessed using the [][]
operator, which returns a reference
to the element at the given row and column:
//Create new matrix
LouLib::Math::Matrix A({{1,2},{3,4}});
//Get elements
double firstElement = A[0][0];
double secondElement = A[0][1];
double thirdElement = A[1][0];
double fourthElement = A[1][1];
After running the example above, the value of firstElement
will be 1, the value of secondElement
will be 2,
the value of thirdElement
will be 3, and the value of fourthElement
will be 4.
The [][]
operator can also be used to edit the elements in a matrix:
//Create new matrix
LouLib::Math::Matrix A({{1, 2, 3},{4,5,6}});
//Edit element
v[0][0] = 10;
The example above will edit the elements of the matrix as follows:
The Matrix class also contains getRow
and getCol
methods that the return the row/column vector at the given index:
//Create new matrix
LouLib::Math::Matrix A({{1, 2, 3},{4,5,6}});
//Get first column
LouLib::Math::Vector v1 = A.getCol(0);
//Get first row
LouLib::Math::Vector v2 = A.getRow(0);
The example above will result in the following two vectors:
Matrix methods
The Matrix
class contains the following methods:
.rows()
- Returns the number of rows in the matrix.cols()
- Returns the number of columns in the matrix.transpose()
- Returns the transpose of the matrix.norm()
- Returns the frobenius norm of the matrix: \(\sqrt{\sum\limits_{i=0}^{m-1} \sum\limits_{j=0}^{n-1} (a_{i,j})^2}\).det()
- Returns the determinant of the matrix (only works for square matrices).inverse()
- Returns the inverse of the matrix (only works if the matrix is invertible)
Matrix operators
The Matrix
class contains the following operators:
+
- Used to add two matrices-
- Used to subtract two matrices*
- Used to multipy two matrices, multiply a matrix by a scalar, or multiply a vector by a matrix