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:

\[\begin{split}\textbf{v} = \begin{bmatrix} x_0 \\ x_1 \\ \vdots \\ x_{n-1} \end{bmatrix}\end{split}\]

Creating a vector

The Vector class provides four different constructors for creating a new Vector:

  1. Create a new vector and fill in the values:

LouLib::Math::Vector v1(3);
v1[0] = 1;
v1[1] = 2;
v1[2] = 3;
  1. Create a vector from std::initializer_list<double>:

LouLib::Math::Vector v2({1, 2, 3});
  1. 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);
  1. Create a copy of an already existing vector:

LouLib::Math::Vector v4(v1);

All four of the examples above create the same vector:

\[\begin{split}\textbf{v}_1 = \textbf{v}_2 = \textbf{v}_3 = \textbf{v}_4 = \begin{bmatrix} 1 \\ 2 \\ 3 \end{bmatrix}\end{split}\]

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:

\[\begin{split}\textbf{v} = \begin{bmatrix} 1 \\ 2 \\ 3 \end{bmatrix} \quad\enspace \boldsymbol{\Longrightarrow} \quad\enspace \textbf{v} = \begin{bmatrix} 5 \\ 2 \\ 3 \end{bmatrix}\end{split}\]

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