This post is a basic introduction to the Vector
structure in linalgcpp.
linalgcpp supports the templated Vector<T>
, but all the examples in this post will use the most common Vector<double>
:
Construction
There are several constructors available.
The default constructor creates a Vector
of zero dimension:
To create a Vector
of any finite dimension \(n\), we pass in the dimension as a parameter to the constructor.
This will create a zero filled vector of the given dimension:
If we wish to fill the \(n\) dimension vector with some other initial value, we can pass in the value after the dimension:
If we know the values of the vector beforehand, we can directly initialize a Vector
with those values:
Indexing
To access an individual element of a Vector
, we use the array index operator []
.
For example, let vector \(x = \begin{bmatrix} 1 \\ 7 \\ 0 \\ 2 \end{bmatrix}\). To access the \(i\)th element of \(x\):
It is important to note that this is 0-based indexing. That is, the first element is \(x_0\). In the above example, \(x_1\) will set \(x_i := 7.0\).
Scaling
To scale a given vector, we simply use the overloaded *
operator:
We can also scale in place:
Division is also supported:
And division in place:
Addition
To add two vectors, we use the overloaded +
operator:
This can also be done in place:
Subtraction works similarly:
This can also be done in place:
Inner Product
To compute the inner product of two vectors, we use the Mult
function.
For example, let vector \(x = \begin{bmatrix} 1 \\ 7 \\ 0 \\ 2 \end{bmatrix}\) and let vector \(y = \begin{bmatrix} 3 \\ 4 \\ 1 \\ 8 \end{bmatrix}\).
To compute the inner product \(\alpha = y^Tx\):
\(L_2\) Norm
We can put some of these operations together to finally compute something useful.
For example, given a vector \(x\), we wish to compute
\[\left\Vert x \right\Vert_2 = \sqrt{\sum_{i=0}^{n-1} x_i^2} = \sqrt{x^Tx}\]In code, this would be:
Finally, suppose we wish to normalize the vector \(x\) such that \(\left\Vert x \right\Vert_2 = 1.0\):