Matrixes can be used similarly to vectors:
If the dimensions of the matrixes are not known at build time, you would instead write:
Once you have matrixes, you need to initialize them. A matrix is also a vector, so you can initialize it by indexing into the vector:
You can also use a bidimensional indexing:
Once you have initialized matrixes, you can operate on them:
The operators + and * are merged into the loop. * is the element-wise multiply. For eagerly evaluated vector / matrix products you should use the operator dot.
Note that fusion of operators will not work with dot(Matrix, Matrix) or dot(Matrix, Vector), since both operations return an owning, eagerly evaluated result. Vector dot products return a scalar.
For a matrix times vector product that must be fused with vector operations, use the lazy matvec operator:
matvec returns a non-owning expression. In this example, the matrix-vector product is accumulated directly into result without allocating a temporary vector. The operands must remain alive until the complete expression is evaluated. Use dot(matrix, vector) when an owning result is required.
We can create virtual vectors which are view of some slices of the matrix.
To set the second row to 0.0f, you can do:
To set the odd elements of the 3rd row to 0.0f we can do:
The first argument 2 is the row number (starting from 0).
The second argument 1 is where is the row we start the view : element 1.
<2> is the stride known at built time.
The row API is:
stop is the index of the first element after the end of the view.
i is the row index
There is a similar API for columns.
Let's set the odd elements of columns 3 to 5.0f:
It is also possible to create a virtual matrix : a view onto a subset of the matrix.
Let's add the bottom right corner of the matrix to itself:
The API is:
You specify the row start and row end, then column start and column end.
Note that the end is the first index after the end of your rows or columns.
No stride is supported for matrix view in this version of the library.
In addition to the vector operations +,- and *, matrixes are supporting more operations:
dot for vector / matrix productsdiagonal to create a diagonal matrix from a vector.identity to create an identity matrixtranspose to create the transposed matrixouter for the outer product of two vectorsThe compiler may use the move semantic to copy the temporary result of the dot function to result.
In this case, no copy would occur and result after the assignment would be a vector allocated by dot so using the TMP_ALLOC .
Unlike dot(matrix, vector), matvec(matrix, vector) is lazy. It participates in the normal one-dimensional fusion loop, so the matrix-vector result can be combined with additions, multiplications, or accumulation without first being stored in a temporary vector. Matrix-matrix products remain eager and continue to use dot.
or