我使用特征库来初始化矩阵,并进行与对角化相关的计算。 到目前为止,我一直使用“按值调用”的方法,即:
现在,我想使用指针动态分配矩阵。 我编写了如下代码:
#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_insteader
,matrix类使用圆括号来索引,而不是文档中提到的方括号。 所以更改
H[i][j] = 1.0;
至
H(i,j) = 1.0;
此外,矩阵已经被动态分配,这里不需要new
。
MatrixXd H(10, 10);