Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Operator + for matrices in C++

I suppose the naive implementation of a + operator for matrices (2D for instance) in C++ would be:

class Matrix {

  Matrix operator+ (const Matrix & other) const {
      Matrix result;
      // fill result with *this.data plus other.data
      return result;
  }
}

so we could use it like

Matrix a;
Matrix b;
Matrix c;

c = a + b;

Right?

But if matrices are big this is not efficient as we are doing one not-necessary copy (return result).

Therefore, If we wan't to be efficient we have to forget the clean call:

c = a + b;

Right?

What would you suggest / prefer ? Thanks.

like image 893
cibercitizen1 Avatar asked Mar 17 '10 16:03

cibercitizen1


People also ask

What is matrix operations in C?

Matrix is a 2D array of numbers arranged in rows and columns. Various operations such as Addition, Subtraction, and Multiplication can be performed on the matrices. Multiplication of two matrices is possible only when the number of columns in the first matrix equals the number of rows in the second matrix.

What is operator of a matrix?

A matrix operator is defined as the operator such that the eigenvalue E of a system with wave function u is an eigenvalue of , i.e., (28) where I is the identity matrix. This matrix operator including two-body particle interactions is the starting entity enabling the studies of all linear properties of a given system.

What is matrix multiplication in C?

Matrix multiplication in C: We can add, subtract, multiply and divide 2 matrices. To do so, we are taking input from the user for row number, column number, first matrix elements and second matrix elements. Then we are performing multiplication on the matrices entered by the user.


1 Answers

The C++ standard gives permission for the compiler to elide the unnecessary copy in this case (it's called the "named return value optimization", usually abbreviated to NRVO). There's a matching "RVO" for when you return a temporary instead of a named variable.

Nearly all reasonably recent C++ compilers implement both NRVO and RVO, so generally speaking you can ignore the fact that this construct wouldn't otherwise be particularly efficient.

Edit: I was, of course, talking about the copy involved in returning the new matrix holding the result of the addition. You probably do want to either pass the input by const reference:

Matrix operator+(Matrix const &other) const { 
    Matrix result;
    // ...
    return result;
}

...or else, pass by value, but return the passed value:

Matrix operator+(Matrix other) const { 
    other += *this;
    return other;
}

Note that this depends on commutativity though (i.e., it's really doing b+a instead of a+b) so while it's fine for addition, it won't work for some other operations.

like image 186
Jerry Coffin Avatar answered Sep 21 '22 09:09

Jerry Coffin