How to apply the same operations to rows in a matrix to columns without code duplicaton?

25 Views Asked by At

I frequently work with 2D matrices, and frequently find myself having to check validity (validity depends on the use case, but for the purpose of this question, it may not matter) of rows and columns. In such cases the validity of a row/column is the defined the same way for rows as it is for columns.

I usually end up writing 2 utility functions:

bool check_rows_valid() {
  for (int i = 0; i < NUM_ROWS; ++i) {
    // check row i, mat[i] is valid depending on how validity is defined
  }
}

bool check_cols_valid() {
  for (int j = 0; j < NUM_COLS; ++j) {
    // check column j mat[:][j] is valid depending on how validity is defined
  }
}

So I end up writing essentially the same utility for column and row. Is there a cleaner way to do this with a single utility function that can cover both rows & columns?

1

There are 1 best solutions below

0
MJTech On

That looks good, but to avoid a large code block in the for loops, try doing something similar to this example:

template <type T>
class Intermediate
{
public:
    void Intermediate(size_t i) : _i(i) {};
    T operator[](size_t j) { return mat[_i][j]; }
/* ... */
}

template <type T>
class InverseIntermediate : public Intermediate
{
public:
    void InverseIntermediate(size_t i) : _i(i) {};
    T operator[](size_t j) { return mat[j][_i]; } // Reversed
/* ... */
}

template <type T>
class Matrix
{
public:
    Intermediate<T> operator[](size_t i) { return Intermediate(i); }
/* ... */
}

template <type T>
class InverseMatrix : public Matrix
{
public:
    InverseIntermediate<T> operator[](size_t i) { return InverseIntermediate(i); }
/* ... */
}

Then, operate on the Matrix object in the case of checking row validity, and operate on the InverseMatrix object in the case of checking column validity.

bool check_rows_valid(Matrix mat)
{
     for (size_t i = 0; i < NUM_ROWS; ++i)
    {
        // check row i, mat[i] is valid depending on how validity is defined
    }
}

bool check_cols_valid(Matrix mat)
{
    return check_rows_valid(InverseMatrix(mat));
}

NOTE: This code is not complete! This is just a model to illustrate the point and you need to provide the rest yourself, so I did not try as hard to rigorously hold to C++ standards, especially since this problem is language agnostic.