Vector
The Vector
class is used to store a mathematical vector. Each instance of Vector
represents an \(n\)-dimensional
vector that can be written as:
Creating a vector
The Vector
class provides four different constructors for creating a new Vector
:
Create a new vector and fill in the values:
LouLib::Math::Vector v1(3);
v1[0] = 1;
v1[1] = 2;
v1[2] = 3;
Create a vector from
std::initializer_list<double>
:
LouLib::Math::Vector v2({1, 2, 3});
Create a vector from
std::vector<double>
:
std::vector<double> vectorData;
list.push_back(1);
list.push_back(2);
list.push_back(3);
LouLib::Math::Vector v3(vectorData);
Create a copy of an already existing vector:
LouLib::Math::Vector v4(v1);
All four of the examples above create the same vector:
Accessing elements in a vector
The elements of a vector can be accessed using the []
operator, which returns a
reference to the element at the given index:
//Create new vector
LouLib::Math::Vector v({1, 2, 3});
//Get elements
double firstElement = v[0];
double secondElement = v[1];
double thirdElement = v[2];
After running the example above, the value of firstElement
will be 1, the value of secondElement
will be 2, and the value of thirdElement
will be 3.
The []
operator also can be used to edit the elements in a vector:
//Create new vector
LouLib::Math::Vector v({1, 2, 3});
//Edit element
v[0] = 5;
The example above will edit the elements of the vector as follows:
Vector Methods
The Vector
class contains the following methods:
.size()
- Returns the dimension/size of the vector.norm()
- Returns the norm/magnitude of the vector: \(\sqrt{x_0^2 + x_1^2 + \dots + x_{n-1}^2}\).normalize()
- Returns a vector with same direction but with magnitude 1: \(\frac{1}{\|\textbf{v}\|} \textbf{v}\)
Vector Operators
The Vector
class contains the following operators:
+
- Used to add two vectors-
- Used to subtract two vectors*
- Used to find the dot product of two vectors, multiply a vector by a scalar, or multiply a vector by a matrix