2

How to increment a column of a dynamic matrix by one, as an in place operation (without creating copies/intermediates) ?

Attempt:

#include <Eigen/Dense>
#include <iostream>
#include <stdint.h>
int main(void){
    Eigen::MatrixXf A;
    A = Eigen::MatrixXf::Random(3, 5);
    std::cout << A << std::endl << std::endl;
    A.col(1) = A.col(1)*2; //this works.
    A.col(1) = A.col(1) + 1; //this doesn't work.
    std::cout << A << std::endl;
}
hamster on wheels
  • 2,771
  • 17
  • 50

1 Answers1

3

I found a way to do this. But I don't know if the operation is in place.

This is similar to eigen: Subtracting a scalar from a vector

#include <Eigen/Dense>
#include <iostream>
int main(void){
    Eigen::MatrixXf A;
    A = Eigen::MatrixXf::Random(3, 5);
    std::cout << A << std::endl << std::endl;

    A.col(1) = A.col(1)*2;
    A.col(1) = A.col(1) + Eigen::VectorXf::Ones(3);
    std::cout << A << std::endl;
}

Another way is to use array operation. This way seem better (I guess).

https://eigen.tuxfamily.org/dox/group__TutorialArrayClass.html

#include <Eigen/Dense>
#include <iostream>
int main(void){
    Eigen::MatrixXf A;
    A = Eigen::MatrixXf::Random(3, 5);
    std::cout << A << std::endl << std::endl;

    A.array() += 1;
    A.col(1).array() += 100;

    std::cout << A << std::endl;
}
Community
  • 1
  • 1
hamster on wheels
  • 2,771
  • 17
  • 50
  • 2
    Using the `array()` approach is what I would recommend. If you are mostly doing element-wise operations, consider storing `A` as `Eigen::ArrayXXf` from the beginning. You can later still access `A` as matrix via the `matrix()` method. – chtz Oct 03 '16 at 19:12