I have been developing a control software in C++ and for implementation of the control algorithms I need basic matrix operations like addition, subtraction, multiplication and multiplication by scalar.
Due to the fact that the application is the real time application I need to avoid the dynamic memory allocation so I have decided to exploit the C++ templated class and the nontype parameters
template <class T, uint8_t ROWS, uint8_t COLUMNS>
class Matrix
{
public:
T array[ROWS][COLUMNS];
Matrix<T, ROWS, COLUMNS> operator+(const Matrix<T, ROWS, COLUMNS> &m) const
{
Matrix<T, ROWS, COLUMNS> result;
for (uint8_t row = 0; row < ROWS; row++) {
for (uint8_t column = 0; column < COLUMNS; column++) {
result.array[row][column] = array[row][column] + m.array[row][column];
}
}
return result;
}
Matrix<T, ROWS, COLUMNS> operator-(const Matrix<T, ROWS, COLUMNS> &m) const
{
Matrix<T, ROWS, COLUMNS> result;
for (uint8_t row = 0; row < ROWS; row++) {
for (uint8_t column = 0; column < COLUMNS; column++) {
result.array[row][column] = array[row][column] - m.array[row][column];
}
}
return result;
}
template <uint8_t N>
Matrix<T, ROWS, N> operator*(const Matrix<T, COLUMNS, N> &m) const
{
Matrix<T, ROWS, N> result;
for (uint8_t row = 0; row < ROWS; row++) {
for (uint8_t column = 0; column < N; column++) {
result.array[row][column] = 0;
for (uint8_t element = 0; element < COLUMNS; element++) {
result.array[row][column] +=
array[row][element] * m.array[element][column];
}
}
}
return result;
}
friend Matrix<T, ROWS, COLUMNS> operator*(double k,
const Matrix<T, ROWS, COLUMNS> &m)
{
Matrix<T, ROWS, COLUMNS> result;
for (uint8_t row = 0; row < ROWS; row++) {
for (uint8_t column = 0; column < COLUMNS; column++) {
result.array[row][column] = k * m.array[row][column];
}
}
return result;
}
friend Matrix<T, ROWS, COLUMNS> operator*(const Matrix<T, ROWS, COLUMNS> &m,
double k)
{
return k*m;
}
};
I have doubts regarding the decision to have the matrix itself i.e. the array
as a public member of the Matrix
classes.