Reputation: 1825
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?
Upvotes: 1
Views: 1330
Reputation: 10596
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)
{ ...
Upvotes: 2