Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Eigen and std::vector

Tags:

c++

eigen

I have a matrix, which is given as:

std::vector<std::vector<std::complex<double>>> A;

And I want to map that to the Eigen linear algebra library like this:

Eigen::Map<Eigen::MatrixXcd, Eigen::RowMajor> mat(A.data(),51,51);

But the code fails with

error: no matching function for call to        
‘Eigen::Map<Eigen::Matrix<std::complex<double>, -1, -1>, 1>::

Is there anyway to convert a vector of a vector so that Eigen can use it?

like image 513
user1876942 Avatar asked Nov 12 '15 09:11

user1876942


People also ask

Is std::vector fast?

A std::vector can never be faster than an array, as it has (a pointer to the first element of) an array as one of its data members. But the difference in run-time speed is slim and absent in any non-trivial program. One reason for this myth to persist, are examples that compare raw arrays with mis-used std::vectors.

Is std::vector an array?

std::vector is a template class that encapsulate a dynamic array1, stored in the heap, that grows and shrinks automatically if elements are added or removed.

How do you initialize a vector in Eigen?

Eigen offers a comma initializer syntax which allows the user to easily set all the coefficients of a matrix, vector or array. Simply list the coefficients, starting at the top-left corner and moving from left to right and from the top to the bottom. The size of the object needs to be specified beforehand.

What is Eigen column vector?

Vectors. As mentioned above, in Eigen, vectors are just a special case of matrices, with either 1 row or 1 column. The case where they have 1 column is the most common; such vectors are called column-vectors, often abbreviated as just vectors. In the other case where they have 1 row, they are called row-vectors.


1 Answers

Eigen uses contiguous memory, as does std::vector. However, the outer std::vector contains a contiguous set of std::vector<std::complex<double> >, each pointing to a different set of complex numbers (and can be different lengths). Therefore, the std "matrix" is not contiguous. What you can do is copy the data to the Eigen matrix, there are multiple ways of doing that. The simplest would be to loop over i and j, with a better option being something like

Eigen::MatrixXcd mat(rows, cols);
for(int i = 0; i < cols; i++)
    mat.col(i) = Eigen::Map<Eigen::VectorXcd> (A[i].data(), rows);
like image 140
Avi Ginsburg Avatar answered Sep 21 '22 09:09

Avi Ginsburg