Search code examples
c++matrixeigen

C++ Eigen. Need advice


Need some advice about Eigen.

I want to create matrix from coefficients of vectors (one-column matrices) 'a' and 'b' in this way:

| a0*b0 | a0*b1 | a0*b2 | ... | a0*bn |
| a1*b0 | a1*b1 | a1*b2 | ... | a1*bn |
| a2*b0 | a2*b1 | a2*b2 | ... | a2*bn |
| ...   | ...   | ...   | ... | ...   |
| am*b0 | am*b1 | am*b2 | ... | am*bn |

If simply, I'd like to create multiplication table made up from two vectors and add it to another matrix.

How can I do it in the most efficient and elegant way ?

I found out two ways:

Matrix<float, -1, 1> a = new Matrix<float, -1, 1>(6);
Matrix<float, -1, 1> b = new Matrix<float, -1, 1>(4);
MatrixXf SomeNotEmptyMatrix = new MatrixXf(6, 4);

SomeNotEmptyMatrix += a.asDiagonal()*MatrixXf::Constant(6, 4, 1.0)*b.asDiagonal();

and

Matrix<float, -1, 1> a = new Matrix<float, -1, 1>(6);
Matrix<float, -1, 1> b = new Matrix<float, -1, 1>(4);
MatrixXf SomeNotEmptyMatrix = new MatrixXf(6, 4);

for(int32_t i = 0; i < 4; i++){
  SomeNotEmptyMatrix.colwise() += a*b(i, 0);
}

But I don't think these are the best ones. In the first instance temporary matrix MatrixXf::Constant(6, 4, 1.0) will be allocated. In the second instance I use external loop.


Solution

  • This is called the outer product, and it can be done from two vectors in Eigen just using the standard matrix product:

    MatrixXf result = a * b.transpose();
    

    Note that this is the oppose way round than a.transpose() * b which you may be more familiar seeing, which is the dot product resulting in a single scalar.