-
Notifications
You must be signed in to change notification settings - Fork 6
Working with matrices
Martijn Koopman edited this page Jun 6, 2019
·
10 revisions
Required include for matrices:
#include <spatium/Matrix.h>
The code below constructs the following 2-by-3 matrix:
1 2 3
4 5 6
Method 1: Explicitly by constructor
spatium::Matrix m(2, 3);
m(0,0) = 1; m(0,1) = 2; m(0,2) = 3;
m(1,0) = 4; m(1,1) = 5; m(1,2) = 6;
Method2: Constructor with initalizer list
spatium::Matrix m({{1, 2, 3}, {4, 5, 6}});
Method 3: Implicitly via initalizer list and assignment
spatium::Matrix m = {{1, 2, 3}, {4, 5, 6}};
spatium::Matrix m(4, 1);
m(0,0) = 1;
m(1,0) = 2;
m(2,0) = 3;
spatium::Vector3 v = m;
Construct the matrix:
spatium::Matrix m1 = {
{ 1, 2, 3 },
{ 4, 5, 6}
};
Transpose
spatium::Matrix m2 = m1.transposed();
Result:
1 4
2 5
3 6
Multiply
Multiply by another matrix:
spatium::Matrix m3 = m1 * m2;
Result:
14 32
32 77
Multiply by scalar
Multiply by scalar 2
:
spatium::Matrix m4 = m3 * 2;
Result:
28 64
64 154
Calculate inverse
spatium::Matrix m5 = {
{3 , 3.2},
{3.5, 3.6}
};
Matrix m6 = m5.inverse();
Result:
-9 8
8.75 -7.5
Several functions of class Matrix can throw std::out_of_bounds
exception. These are:
-
determinant()
- If matrix is not square -
inverse()
- If matrix is not square or it is singular -
operator()(int, int)
- Access element by index - Index out of bounds -
operator+(Matrix)
- Add matrices - Dimensions mismatch -
operator+(Matrix)
- Subtract matrices - Dimensions mismatch -
operator*(Matrix)
- Multiply matrices - Column count mismatch with row count of other matrix
Exception: Accessing element by index
spatium::Matrix matrix = {
{ 1, 2, 3 },
{ 4, 5, 6 }
};
try {
double val = matrix(1, 3);
}
catch(std::out_of_range e)
{
// Column range is 0 - 2 (3 is out of bounds)
}