Skip to main content
We’ve updated our Terms of Service. A new AI Addendum clarifies how Stack Overflow utilizes AI interactions.
Tweeted twitter.com/StackCodeReview/status/1382619827257348099
Source Link
Student
  • 395
  • 2
  • 11

Implementation of the basic matrix operations for embedded application in C++

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.