Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matrix with unknown number of rows and columns Eigen library

Tags:

c++

eigen

I want to read data from a file into a matrix in Eigen. I have coded everything but there is one problem that I encounter. I don't know yet beforehand how many data points are in the file, so I want to be able to initialize a matrix without specifying its size. I know that the following way of intializing a matrix works in Eigen:

MatrixXd A;

But now if I then do for instance

A << 1, 2,
     4, 7;

It doesn't work. I had hoped that it would recognise it as a 2x2 matrix in this example, so that I could then work with it. So basically my question is, how can I add data to A, without having to specify its size?

like image 206
dreamer Avatar asked May 01 '14 18:05

dreamer


2 Answers

If what you want is read data from a file which does not specify the matrix size explicitly, then I would recommend to push back the entries in a std::vector and at the end of the parsing copy the data from the std::vector using Map:

MatrixXf A;
std::vector<float> entries;
int rows(0), cols(0);
while(...) { entries.push_back(...); /* update rows/cols*/ }
A = MatrixXf::Map(&entries[0], rows, cols);

This will be much more efficient than calling conservativeResize every times.

like image 171
ggael Avatar answered Oct 01 '22 15:10

ggael


From the Eigen Tutioral about Matrix


Of course, Eigen is not limited to matrices whose dimensions are known at compile time. The RowsAtCompileTime and ColsAtCompileTime template parameters can take the special value Dynamic which indicates that the size is unknown at compile time, so must be handled as a run-time variable. In Eigen terminology, such a size is referred to as a dynamic size; while a size that is known at compile time is called a fixed size. For example, the convenience typedef MatrixXd, meaning a matrix of doubles with dynamic size, is defined as follows:

typedef Matrix<double, Dynamic, Dynamic> MatrixXd;

And similarly, we define a self-explanatory typedef VectorXi as follows:

typedef Matrix<int, Dynamic, 1> VectorXi;

You can perfectly have e.g. a fixed number of rows with a dynamic number of columns, as in:

Matrix<float, 3, Dynamic>

Here is an example I just quickly made:

Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic> myMatrix;
myMatrix.resize(1, 1);
myMatrix(0, 0) = 1.0;
myMatrix.resize(2, 2);
myMatrix(1, 1) = 1.0;
myMatrix.resize(3, 3);
myMatrix(2, 2) = 1.0;
myMatrix.resize(4, 4);
myMatrix(3, 3) = 1.0;
like image 36
Caesar Avatar answered Oct 01 '22 15:10

Caesar