C++ 我应该如何在 Eigen 中初始化一个大矩阵的内容?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27005322/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 20:43:17  来源:igfitidea点击:

How should I initialize the contents of a large matrix in Eigen?

c++eigen

提问by andyras

I am trying to initialize a matrix (using the Eigen library) to have a nonzero value when I create it. Is there a nice way to do this without a for loop?

我正在尝试初始化一个矩阵(使用 Eigen 库)以在创建它时具有非零值。有没有没有 for 循环的好方法?

For example, if I wanted to initialize the whole matrix to 1.0, I would like to do something like:

例如,如果我想将整个矩阵初始化为 1.0,我想执行以下操作:

Eigen::MatrixXd mat(i,j) = 1.0;

or

或者

Eigen::MatrixXd mat(i,j);
mat += 1.0;

(I am used to this type of thing in MATLAB, and it would make Eigen even nicer to use than it already is. I suspect there is a built-in method somewhere that does this, that I have not found.)

(我已经习惯了 MATLAB 中的这种类型的东西,它会使 Eigen 比现在更好用。我怀疑某处有一个内置方法可以做到这一点,但我还没有找到。)

A sub-question to this question would be how to set a block of matrix elements to a set value, something ilke:

这个问题的一个子问题是如何将矩阵元素块设置为设定值,例如:

mat.block(i,j,k,l) = 1.0;

回答by andyras

As so often happens I found the answer in the docs within thirty seconds of posting the question. I was looking for the Constantfunction:

正如经常发生的那样,我在发布问题后的 30 秒内在文档中找到了答案。我正在寻找Constant功能

Eigen::MatrixXd mat = Eigen::MatrixXd::Constant(i, j, 1.0);

mat.block(i,j,k,l) = Eigen::MatrixXd::Constant(i, j, 1.0);

回答by Jake0x32

Eigen::MatrixXd::Ones(), Eigen::MatrixXd::Zero()and Eigen::MatrixXd::Random()can all give you what you want, creating the Matrix in a dynamic way.

Eigen::MatrixXd::Ones()Eigen::MatrixXd::Zero()并且Eigen::MatrixXd::Random()都可以给你你想要的,以动态的方式创建矩阵。