Search code examples
c++eigen

How could I subtract a 1xN eigen matrix from a MxN matrix, like numpy does?


I could not summarize a 1xN matrix from a MxN matrix like I do in numpy.

I create a matrix of np.arange(9).reshape(3,3) with eigen like this:

int buf[9];
for (int i{0}; i < 9; ++i) {
    buf[i] = i;
}
m = Map<MatrixXi>(buf, 3,3);

Then I compute mean along row direction:

    m2 = m.rowwise().mean();

I would like to broadcast m2 to 3x3 matrix, and subtract it from m, how could I do this?


Solution

  • You need to use appropriate types for your values, MatrixXi lacks the vector operations (such as broadcasting). You also seem to have the bad habit of declaring your variables well before you initialise them. Don't.

    This should work

    std::array<int, 9> buf;
    std::iota(buf.begin(), buf.end(), 0);
    
    auto m = Map<Matrix3i>(buf.data());
    auto v = m.rowwise().mean();
    auto result = m.colwise() - v;