sap7889
sap7889

Reputation: 21

Using a pointer to dynamically allocate Matrices in c++ in presence of eigen library

I use Eigen library to initialize matrices and do calculations related to diagonalization and such. Till now, I have been using 'call by value' method, i.e. :

  1. I define a a complex double NxN matrix with MatrixXcd H(N,N).
  2. Then I call a routine like SelfAdjointMatrixSolver es(H).
  3. Finally I obtain the eigenvalues with es.eigenvalues().

Now, I would like to dynamically allocate matrices using pointer. I wrote the following code :

#include <iostream>
#include <complex>
#include <cmath>
#include<math.h>
#include<stdlib.h>
#include<time.h>
#include<Eigen/Dense>
#include<fstream>
#include<random>

using namespace std;
using namespace Eigen;



int main()
 {
 int i,j,k,l;//for loops
 MatrixXd *H = NULL;
 H = new MatrixXd(10,10);
 if (!H) 
 cout << "allocation of memory failed\n"; 
 else
 {
 for(i=0;i<10;i++)
  {
   for(j=0;j<10;j++)
    {
     H[i][j]=1.0;
    }
  }
 }
 return 0;
}

I get the following error messages :

In file included from eigen/Eigen/Core:347:0,
                 from eigen/Eigen/Dense:1,
                 from test.cpp:7:
eigen/Eigen/src/Core/DenseCoeffsBase.h: In instantiation of ‘Eigen::DenseCoeffsBase<Derived, 1>::Scalar& Eigen::DenseCoeffsBase<Derived, 1>::operator[](Eigen::Index) [with Derived = Eigen::Matrix<double, -1, -1>; Eigen::DenseCoeffsBase<Derived, 1>::Scalar = double; Eigen::Index = long int]’:
test.cpp:32:13:   required from here
eigen/Eigen/src/Core/util/StaticAssert.h:32:40: error: static assertion failed: THE_BRACKET_OPERATOR_IS_ONLY_FOR_VECTORS__USE_THE_PARENTHESIS_OPERATOR_INSTEAD
     #define EIGEN_STATIC_ASSERT(X,MSG) static_assert(X,#MSG);
                                        ^
eigen/Eigen/src/Core/DenseCoeffsBase.h:406:7: note: in expansion of macro ‘EIGEN_STATIC_ASSERT’
       EIGEN_STATIC_ASSERT(Derived::IsVectorAtCompileTime,

How should I solve this problem? Is my mistake is in defining the pointer or in assigning the values?

Upvotes: 0

Views: 463

Answers (1)

Cory Kramer
Cory Kramer

Reputation: 117876

As this assertion says THE_BRACKET_OPERATOR_IS_ONLY_FOR_VECTORS__USE_THE_PARENTHESIS_OPERATOR_INSTEAD the matrix class uses parentheses to index, not square braces as noted in the docs. So change

H[i][j] = 1.0;

to

H(i,j) = 1.0;

Also the matrix is already dynamically allocated, no need for new here.

MatrixXd H(10, 10);

Upvotes: 2

Related Questions