【问题标题】:Using a pointer to dynamically allocate Matrices in c++ in presence of eigen library在存在特征库的情况下使用指针在 C++ 中动态分配矩阵
【发布时间】:2020-06-22 11:27:29
【问题描述】:

我使用 Eigen 库来初始化矩阵并进行与对角化等相关的计算。到目前为止,我一直在使用“按值调用”方法,即:

  1. 我用 MatrixXcd H(N,N) 定义了一个复数双 NxN 矩阵。
  2. 然后我调用像 SelfAdjointMatrixSolver es(H) 这样的例程。
  3. 最后我用 es.eigenvalues() 获得了特征值。

现在,我想使用指针动态分配矩阵。我写了以下代码:

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

我收到以下错误消息:

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,

我应该如何解决这个问题?我的错误是定义指针​​还是赋值?

【问题讨论】:

  • 变量H 不是MatrixXd 对象,但*H 是。尝试使用(*H)[i][j]
  • 看来这行得通,非常感谢!

标签: c++ pointers eigen dynamic-memory-allocation


【解决方案1】:

正如这个断言所说的THE_BRACKET_OPERATOR_IS_ONLY_FOR_VECTORS__USE_THE_PARENTHESIS_OPERATOR_INSTEAD,矩阵类使用括号来索引,而不是方括号as noted in the docs。所以改变

H[i][j] = 1.0;

H(i,j) = 1.0;

另外矩阵已经动态分配了,这里不需要new

MatrixXd H(10, 10);

【讨论】:

  • 所以我以前经常这样做。但我现在想采用指针方法,因为我必须对 2744 x 2744 矩阵进行对角化,获得特征值和特征向量,从特征向量计算特定量。我必须重复这个过程 300-400 次。到目前为止,我已经用 512 x 512 矩阵完成了这个过程,花了 2-3 个小时。但是对于 2744 x 2744 矩阵,它已经持续了 20-22 小时。那么如何动态分配和释放内存,让进程变得更快呢?
  • 矩阵类已经动态分配它管理的底层数组。我保证,用new 分配矩阵不会让你的计算更快。
  • 好的,谢谢。有什么方法可以释放哈密顿量使用后占用的内存?就像我们在 c 中使用 free() 或在 c++ 中使用 delete[] 一样,对于特征定义的矩阵有没有这样的等价物?
  • 你应该可以通过H.resize(0,0)来清除它
  • 添加-O3 例如启用优化,您可以阅读更多关于here
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-02-22
  • 2013-05-27
  • 1970-01-01
  • 2020-12-11
  • 2019-06-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多