4
votes

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
1
I cannot make any sense of this. Are you really asking to be able to reserve an area of memory that can hold an arbitrarily sized structure?? That is you want to reserve a block of memory, obtain the base address of that block, and determine its size after having obtained the base address? If so that is impossible.David Heffernan

1 Answers

1
votes

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;
}