如何根据传递给函数的变量定义特征矩阵大小

How to Define an Eigen Matrix size based upon a variable passed to a function

本文关键字:特征 定义 变量 何根 函数      更新时间:2023-10-16

我正在尝试编写需要根据输入定义矩阵大小的代码。显示问题的精简版代码是:

#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 的最后一行中断。

有什么方法可以修改变量的声明或传递,以便能够以这种方式定义矩阵的大小?

根据文档,如果您在编译时不知道矩阵的大小,则需要使用矩阵大小模板参数作为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);
}