如何根据传递给函数的变量定义特征矩阵大小
How to Define an Eigen Matrix size based upon a variable passed to a function
我正在尝试编写需要根据输入定义矩阵大小的代码。显示该问题的代码的精简版本是:
#include <iostream>
#include "eigen/Eigen/Dense"
#include <cmath>
using namespace Eigen;
void matrixname( const int numbRow, const int numbcol);
int main()
{
const int numbRow=5;
const int numbCol=3;
matrixname(numbRow,numbCol);
return 0;
}
void matrixname( const int numbRow, const int numbCol)
{
Matrix<double,numbRow,numbCol> y;
}
尝试编译代码时,返回以下错误:
/main.cpp:20:15: 错误:非类型模板参数不是常量表达式
构建在尝试定义 y 的最后一行中断。
有什么方法可以修改变量的声明或传递以便能够以这种方式定义矩阵的大小?
根据 documentation,如果您在编译时不知道矩阵的大小,则需要使用矩阵大小模板参数作为 Eigen::Dynamic
。
所以你可能需要修改你的函数如下:
void matrixname( const int numbRow, const int numbCol)
{
Matrix<double,Eigen::Dynamic,Eigen::Dynamic> y1(numbRow, numbCol);
// Eigen also provides a typedef for this type
MatrixXd y2(numbRow, numbCol);
}
我正在尝试编写需要根据输入定义矩阵大小的代码。显示该问题的代码的精简版本是:
#include <iostream>
#include "eigen/Eigen/Dense"
#include <cmath>
using namespace Eigen;
void matrixname( const int numbRow, const int numbcol);
int main()
{
const int numbRow=5;
const int numbCol=3;
matrixname(numbRow,numbCol);
return 0;
}
void matrixname( const int numbRow, const int numbCol)
{
Matrix<double,numbRow,numbCol> y;
}
尝试编译代码时,返回以下错误:
/main.cpp:20:15: 错误:非类型模板参数不是常量表达式
构建在尝试定义 y 的最后一行中断。
有什么方法可以修改变量的声明或传递以便能够以这种方式定义矩阵的大小?
根据 documentation,如果您在编译时不知道矩阵的大小,则需要使用矩阵大小模板参数作为 Eigen::Dynamic
。
所以你可能需要修改你的函数如下:
void matrixname( const int numbRow, const int numbCol)
{
Matrix<double,Eigen::Dynamic,Eigen::Dynamic> y1(numbRow, numbCol);
// Eigen also provides a typedef for this type
MatrixXd y2(numbRow, numbCol);
}