c++matrixvectoreigen

How to subtract mean vector from matrix


I'm having trouble figuring out: How to do a broadcast vector subtraction from a matrix using the C++ lib Eigen?

When I try something like this:

  Vector3d mean;
  mean << 2, 3, -1;

  MatrixXd pts(5, 3);
  pts << 0, 0, 0,
         1, 0, 0,
         0, 1, 0,
         0, 0, 1,
         1, 1, 0;

  MatrixXd results(5, 3);
  results = pts.colwise() - mean;

I get the following result:

-2.00000 -2.00000 -2.00000
-2.00000 -3.00000 -3.00000
1.00000 2.00000 1.00000
-2.00000 -2.00000 ovf
-3.00000 -3.00000 0.00000

What am I doing wrong? Thanks!


Solution

  • If I understand the question correctly, you are trying to subtract the mean vector from each row of pts matrix. The problem is that you are using colwise() instead of rowwise().

        using Eigen::MatrixXd;
        using Eigen::Vector3d;
    
        Vector3d mean;
        mean << 2, 3, -1;
    
        MatrixXd pts(5, 3);
        pts << 0, 0, 0,
                1, 0, 0,
                0, 1, 0,
                0, 0, 1,
                1, 1, 0;
    
        MatrixXd results(5, 3);
        results = pts.rowwise() - mean.transpose();
    

    This code produces:

    -2 -3  1
    -1 -3  1
    -2 -2  1
    -2 -3  2
    -1 -2  1