Search code examples
c++matrixeigen

Eigen subtracting vector from matrix columns


Matrix linesP0 is 3xN. I want to subtract it from vector planeP0 which is 3x1. Is there any smarter and faster way to do this?

Now I'm using a for loop. Sample code below:

MatrixXf temp(linesP0.rows(), linesP0.cols());
for (int i = 0; i < linesP0.cols(); i++)
{
    temp.col(i) = planeP0 - linesP0.block<3, 1>(0, i);
}

I tried to use colwise() but didn't work.


Solution

  • You can use .colwise() to do this, you just have to be a little creative.

    Vector3d v      = Vector3d(1.0, 2.0, 3.0);
    Matrix3d m      = Matrix3d::Random();
    Matrix3d result = (-m).colwise() + v;
    std::cout << result << std::endl;
    

    Sample result:

    v = [1 2 3]' (3x1)
    m = [1 1 1; 2 2 2]' (3x2)
    result = [0 1 2; -1 0 1]' (3x2)