我正在嘗試切換我的代碼并開始在 C 中使用 Eigen 庫,因為我聽說它對矩陣非常有用。現在我的舊 C 代碼主要使用 fftw_malloc 來初始化我的陣列,如下所示:
static const int nx = 10;
static const int ny = 10;
double *XX;
XX = (double*) fftw_malloc(nx*ny*sizeof(double));
memset(XX, 42, nx*ny* sizeof(double));
for(int i = 0; i< nx; i ){
for(int j = 0; j< ny 1; j ){
XX[j ny*i] = (i)*2*M_PI/nx;
}
}
所以我將其更改為以下內容,
Matrix <double, nx, ny> eXX;
eXX.setZero();
for(int i = 0; i< nx; i ){
for(int j = 0; j< ny 1; j ){
eXX[j ny*i] = (i)*2*EIGEN_PI/nx;
}
}
然而,這會回傳錯誤:
In file included from /mnt/c/Users/J/Documents/eigen-3.4.0/eigen-3.4.0/Eigen/Core:164,
from /mnt/c/Users/J/Documents/eigen-3.4.0/eigen-3.4.0/Eigen/Dense:1,
from Test.cpp:21:
/mnt/c/Users/J/Documents/eigen-3.4.0/eigen-3.4.0/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, 10, 10>; Eigen::DenseCoeffsBase<Derived, 1>::Scalar = double; Eigen::Index = long int]’:
Test.cpp:134:16: required from here
/mnt/c/Users/J/Documents/eigen-3.4.0/eigen-3.4.0/Eigen/src/Core/DenseCoeffsBase.h:408:36: error: static assertion failed: THE_BRACKET_OPERATOR_IS_ONLY_FOR_VECTORS__USE_THE_PARENTHESIS_OPERATOR_INSTEAD
408 | EIGEN_STATIC_ASSERT(Derived::IsVectorAtCompileTime,
| ^~~~~~~~~~~~~~~~~~~~~
/mnt/c/Users/J/Documents/eigen-3.4.0/eigen-3.4.0/Eigen/src/Core/util/StaticAssert.h:33:54: note: in definition of macro ‘EIGEN_STATIC_ASSERT’
33 | #define EIGEN_STATIC_ASSERT(X,MSG) static_assert(X,#MSG);
| ^
我看到錯誤指向線路:eXX[j ny*i] = (i)*2*EIGEN_PI/nx;
我對 Eigen 還很陌生,并且仍在嘗試了解我的方式,因此任何反饋/建議都會有所幫助。謝謝。
uj5u.com熱心網友回復:
斷言訊息THE_BRACKET_OPERATOR_IS_ONLY_FOR_VECTORS__USE_THE_PARENTHESIS_OPERATOR_INSTEAD已經告訴您錯誤是什么:不要使用operator[],而是使用operator(),如下所示:
#include <Eigen/Core>
int main()
{
static const int nx = 10;
static const int ny = 100;
Eigen::Matrix<double, nx, ny> eXX;
eXX.setZero();
for (int i = 0; i < nx; i ) {
for (int j = 0; j < ny; j ) {
eXX(i, j) = i * 2 * EIGEN_PI / nx;
}
}
}
另請注意,您的代碼具有未定義的行為,因為j回圈<= ny由于 1回圈條件而進入,這意味著最后一次迭代會導致對陣列的越界訪問。事實上,Eigen 發出了一個斷言(在除錯中)。
此外,由于 Eigen 矩陣默認是列主矩陣,因此交換行和列回圈更有效(但當然這只對較大的矩陣有意義):
#include <Eigen/Core>
int main()
{
static const int nx = 10;
static const int ny = 100;
Eigen::Matrix<double, nx, ny> eXX;
eXX.setZero();
for (int j = 0; j < ny; j ) {
for (int i = 0; i < nx; i ) {
eXX(i, j) = i * 2 * EIGEN_PI / nx;
}
}
}
由于這里每一行的元素都具有相同的值,我們也可以使用row()withsetConstant()來簡化代碼:
#include <Eigen/Core>
int main()
{
static const int nx = 10;
static const int ny = 100;
Eigen::Matrix<double, nx, ny> eXX;
for (int i = 0; i < nx; i ) {
eXX.row(i).setConstant(i * 2 * EIGEN_PI / nx);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/490203.html
