Eigen subtracting vector from matrix columns
Asked Answered
B

1

6

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.

Bobseine answered 15/3, 2017 at 13:22 Comment(0)
T
13

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)
Thematic answered 15/3, 2017 at 13:44 Comment(4)
Jacob, can you please take a look at this similar problem: #42936444Tonsillitis
Sure, I posted an answer.Thematic
Any short explanation why is it faster than a for loop?Curler
@Curler Reasons I can conceive of: - Eigen will reliably vectorize, and more importantly, will vectorize in precisely the way that you want it to. Some vectorization patterns can't be discerned by the compiler, because it would have to know how your data looks at runtime - map-like operations make everyone feel warm and fuzzy deep inside, it can be easier to avoid off-by-one bugs - You want to do everything constThematic

© 2022 - 2024 — McMap. All rights reserved.