Search code examples
c++matlabeigeneigen3

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:

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? If it is possible to somehow get rid of both for loops that would be even better. Is that possible?


Solution

  • Using a NullaryExpr you can do this with zero (manual) loops in 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 ...