justik
justik

Reputation: 4255

C++, redefine operator =, assign a submatrix to the matrix

In the class Matrix

typedef std::vector < std::vector <double> > TItems;
class Matrix
{
   private :
             TItems items;

   public:
           double & operator() ( int r, int c ) {return items[r][c];}
           Matrix & operator = (const Matrix A, short r1, short r2, short c1, short c2 )

}

I am trying to redefine the operator = to be able to assign a submatrix to a matrix.

Matrix  & operator = (const Matrix &A, short r1, short r2, short c1, short c2)
{
  Matrix  A_sub( r2 - r1 + 1, c2 - c1 + 1 );

  for ( int i = 0; i < ( r2 - r1 + 1 ); i++ )
  {
    for ( unsigned int j = 0; j < ( c2 - c1 + 1); j++ )
        items[i][j] = A (r1 + i, c1 + j );
  }

  return *this;
 }

But such a definition is impossible...How to fix the problem if such a type of the notation is needed?

Matrix A(8,8), B (3,9), C(3,4), D(2, 3), E (8, 8);, F(8,8)
...
A(1,3,2,5) = B (0,2,5,8) + C(0,2,0, 3) + D;
F = A + E;

Thanks for your help.

Upvotes: 3

Views: 368

Answers (1)

Tom Kerr
Tom Kerr

Reputation: 10720

I would think the simplest solution would be to keep the same types, and just create a method that creates a smaller submatrix (still of type Matrix), copies the values in, and returns it by value.

class Matrix {
public:
  Matrix createSubMatrix(size_t ri, size_t ci, size_t rsz, size_t csz);
};

Then your addition, assignment, etc operations bear no additional overhead in trying to translate some other type.

You'll pay the overhead of the Matrix copy, but I wouldn't stress about that at this point in your life. :)

Upvotes: 1

Related Questions