1

I want to do whats written in the title, I have tried following code:

typedef std::vector<std::vector<std::vector<double>>> Tensor;

// should return a matrix of shape (batch_size, 1840)
Eigen::MatrixXd flatten(Tensor x)
{
    int channels = x.size(); // always 10
    int batch = x[0].size(); // varies
    int columns = x[0][0].size(); // always 184

    Eigen::Matrix<double, Eigen::Dynamic, 1840> matrix;
    for (unsigned int b = 0; b < batch; b++)
    {
        for (unsigned int i = 0; i < columns; i++)
        {
            for (unsigned int c = 0; c < channels; c++)
            {
                matrix << x[c][b][i]; // I also tried this: matrix(b, i+c) = x[c][b][i];
            }
        }
    }
    return matrix;
}

But the code either aborts with abort() has been called message or its giving me an Access violation writing location 0x0000000000000000

Whats the proper way to accomplish what I am trying to do?

Ach113
  • 1,775
  • 3
  • 18
  • 40

1 Answers1

2

You never told the matrix what size it should be. You have to resize the matrix before writing to it.

Eigen::Matrix<double, Eigen::Dynamic, 1840> matrix;
matrix.resize(batch, 1840);
for (unsigned int b = 0; b < batch; b++)
    ...

A second problem with your code is that operator<< does not behave like push_back of std containers. It initializes an entire (properly sized) matrix at once, not with NxMxL calls.

An unrelated performance issue with the code is that the Tensor x is passed by value, incurring a copy. Pass by (const) reference instead:

Eigen::MatrixXd flatten(const Tensor& x)
{ ...
Avi Ginsburg
  • 10,323
  • 3
  • 29
  • 56
  • I see, did not know matrix needed to be resized. I used `=` operator for assignment, and it works like charm. Thanks – Ach113 Feb 25 '20 at 16:15
  • You also might want to look at [this question](https://stackoverflow.com/questions/58577439/eigen-vertical-stacking-rows-into-matrix). – Avi Ginsburg Feb 25 '20 at 16:21
  • Sorry my bad, I did not mean to write this comment, I'll delete it – Ach113 Feb 25 '20 at 17:11