Skip to content

Latest commit

 

History

History
2 lines (2 loc) · 1.88 KB

README.md

File metadata and controls

2 lines (2 loc) · 1.88 KB

MatrixExpressionTemplates

This repository contains a matrix class which uses expression templates.
Expression templates are used mainly to optimize away redundant allocation and deallocation of memory needed only for a temporary objects.
For example, let matrix A = [[1, 2, 3], [4, 5, 6]], and say we no longer need matrix A but want its transpose, i.e. AT = [[1, 4], [2, 5], [3, 6]].
The usual way of going about this is to allocate a new matrix, B = AT and deallocate A.
But we know the data needed to construct B is already placed in memory, so allocating new memory for it would be wasteful.
Instead, we can change the way we view the data such that matrix A would appear to us as being transposed, and we won't have to destroy matrix A in the process.
Instead of allocating a new matrix instance B = AT , we'll create a view-class and use it to simulate AT.
So far so good, but these types of shenanigans are already possible in C++23 using std::mdspan.
A textbook example of another use for expression templates are for matrices which are the result of complicated formulas.
For example, let matrix G = (A + B + C) * (E - D) where all binary operators are element-wise.
Under the usual definitions of operators '+', '*' and '-', each of those operators takes two matrices, X and Y, and produce a new matrix, Z, which is the result of the element-wise calculation on X and Y.
Hence for the calculation above, we're allocating 1 = (A + B), 2 = (1 + C), 3 = (E - D), and 4 = (2 * 3) new matrices, when we really want at most just one new matrix.
Using expression templates we can achieve this desired outcome.