繁体   English   中英

在存在特征库的情况下使用指针在 c++ 中动态分配矩阵

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

我使用 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,

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

正如这个断言所说的THE_BRACKET_OPERATOR_IS_ONLY_FOR_VECTORS__USE_THE_PARENTHESIS_OPERATOR_INSTEAD矩阵 class 使用括号来索引,而不是文档中所述的方括号。 所以改变

H[i][j] = 1.0;

H(i,j) = 1.0;

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

MatrixXd H(10, 10);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM