[英]I need 2 for loops to fill a matrix in Eigen but I can fill it with only 1 for loop in Matlab - can I get rid of the extra for loop?
I am filling an Eigen matrix with the following code:我正在用以下代码填充特征矩阵:
int M = 3;
int N = 4;
MatrixXd A(M, N);
double res = sin(4);
for (int i = 0; i < M; i++) {
for (int j = 0; j < N; j++) {
A(i, j) = sin(i+j);
}
}
In Matlab I only need 1 for loop to do the same thing using vectorization:在 Matlab 中,我只需要 1 个 for 循环就可以使用矢量化来做同样的事情:
M = 3;
N = 4;
N_Vec = 0:(N-1);
A = zeros(M,N);
for i=1:M
A(i,:) = sin((i-1)+N_Vec);
end
Is it possible to do something similar in C++/Eigen so that I can get rid of one of the for loops?是否可以在 C++/Eigen 中做类似的事情,这样我就可以摆脱其中一个 for 循环? If it is possible to somehow get rid of both for loops that would be even better.如果有可能以某种方式摆脱这两个循环,那就更好了。 Is that possible?那可能吗?
Using a NullaryExpr
you can do this with zero (manual) loops in Eigen:使用NullaryExpr
,您可以使用 Eigen 中的零(手动)循环来执行此操作:
Eigen::MatrixXd A = Eigen::MatrixXd::NullaryExpr(M, N,
[](Eigen::Index i, Eigen::Index j) {return std::sin(i+j);});
When compiled with optimization this is not necessarily faster than the manual two-loop version (and without optimization it could even be slower).当使用优化编译时,它不一定比手动的双循环版本快(如果没有优化,它甚至可能更慢)。
You can write int
or long
instead of Eigen::Index
, if that is more readable...您可以编写int
或long
而不是Eigen::Index
,如果这样更具可读性...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.