Ryo Wakatabe
Ryo Wakatabe

Reputation: 147

Reserve dense eigen matrix

I want to "reserve" dense Eigen::MatrixXd, because I can't know the number of rows beforehand. However, "resize" function changes its address and its value dynamically. Is there any idea?

resize.cpp

#include <Eigen/Dense>
#include <iostream>
using namespace std;
using namespace Eigen;
int main(void) {

  VectorXd m;
  for (int i = 0; i < 5; i++) {
    m.resize(m.size()+1);
    m(i) = i;
    cout << m << endl;
    for (int j = 0; j < m.size(); j++) {
      cout << &m(j) << endl;
    }
  }

  return 0;
}

output

0
0xb34010
0
1
0xb34010
0xb34018
0
1
2
0xb34010
0xb34018
0xb34020
5.80399e-317
4.94066e-324
2.122e-314
3
0xb34030
0xb34038
0xb34040
0xb34048

Upvotes: 4

Views: 2568

Answers (1)

Avi Ginsburg
Avi Ginsburg

Reputation: 10596

You can replace the resize method with conservativeResize. This conserves the existing values in the case of reallocation, which does happen from time to time. In order to reserve the desired memory, just reserve the desired length ahead of time:

#include <Eigen/Dense>
#include <iostream>
using namespace std;
using namespace Eigen;
int main(void) {

  int reserveSize = 50;
  VectorXd m(reserveSize);
  for (int i = 0; i < 65; i++) {
    m.conservativeResize(i+1);
    //m.resize(m.size()+1);
    m(i) = i;
    cout << m << endl;
    for (int j = 0; j < m.size(); j++) {
      cout << &m(j) << endl;

    }
  }

  return 0;
}

Upvotes: 3

Related Questions