问题
I'd like to replicate each row of a matrix M
without any copy occurring (i.e. by creating a view):
0 1 0 1
2 3 -> 0 1
2 3
2 3
M.rowwise().replicate(n)
is a shorcut forM.replicate(1,n)
which seems kind of useless.The following snippet does a copy, and cannot work if
M
is an expression.
Eigen::Index rowFactor = 2; Eigen::MatrixXi M2 = Eigen::Map(M.data(), 1, M.size()).replicate(rowFactor, 1); M2.resize(M.rows()*rowFactor, M.cols()) ;
- In some situation, I may use the intermediate view
Eigen::Map<Eigen::MatrixXi>(M.data(), 1, M.size()).replicate(rowFactor, 1)
by reshaping the other operands, but that's not very satisfying.
Is there a proper way to achieve this broadcast view?
回答1:
What you want is essentially a Kronecker product with a matrix of ones. You can use the (unsupported) KroneckerProduct module for that:
#include <iostream>
#include <unsupported/Eigen/KroneckerProduct>
int main() {
Eigen::Matrix2i M; M << 0, 1, 2, 3;
std::cout << Eigen::kroneckerProduct(M, Eigen::Vector2i::Ones()) << '\n';
}
Being 'unsupported' means that the API of the module is not guaranteed to be stable (though this module has not changed since its introduction, I think).
来源:https://stackoverflow.com/questions/45466391/eigen-replicate-broadcast-by-rows