Search code examples
c++eigen

Dot product in Eigen by multiplying by transpose?


I can't seem to make it work, should it?

e.g.:

    Vector3d a;
    Vector3d b;
    ...
    double c = a.transpose() * b;  // Doesn't work
    double c = a.dot(b);  // Seems to work

I'm coming from MATLAB where a'*b is the thing. I can deal with using dot if needed, but I'd like to know if I'm just doing something dumb.


Solution

  • In matlab, a'*b is syntactic sugar for dot(a, b). Note that the requirement for vectors is "they must have the same length" and not that one is a row vector, and one a column. This is the same as Eigen's a.dot(b).

    In Eigen, a.transpose() * b works, it just doesn't return a double but rather a 1x1 matrix. If you wrote it as MatrixXd c = a.transpose() * b; or double c = (a.transpose() * b)[0]; it should work as expected.

    That above paragraph was the case at in Eigen 2 (which apparently OP was using). Since then (Eigen 3), @ggael of course, is right. This answer regarded a general case where the dimensions of a and b are not known at compile time. In the case where Vector3d or VectorXd are used, then double c = a.transpose() * b; works as well, not as stated in the question. With versions <= 2.0.15, the original is correct without any reservations.