C++ 本征如何沿特定维度连接矩阵?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21496157/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Eigen how to concatenate matrix along a specific dimension?
提问by Ran
I have two eigen matrices and I would like to concatenate them, like in matlab cat(0, A, B)
我有两个特征矩阵,我想将它们连接起来,就像在 matlab 中一样 cat(0, A, B)
Is there anything equivalent in eigen?
特征中有什么等价的吗?
Thanks.
谢谢。
回答by ggael
You can use the comma initializer syntax for that.
您可以为此使用逗号初始值设定项语法。
Horizontally:
水平:
MatrixXd C(A.rows(), A.cols()+B.cols());
C << A, B;
Vertically:
垂直:
// eigen uses provided dimensions in declaration to determine
// concatenation direction
MatrixXd D(A.rows()+B.rows(), A.cols()); // <-- D(A.rows() + B.rows(), ...)
D << A, B; // <-- syntax is the same for vertical and horizontal concatenation
For readability, one might format vertical concatenations with whitespace:
为了可读性,可以用空格格式化垂直串联:
D << A,
B; // <-- But this is for readability only.
回答by tangy
I had a slightly different use case: To vertically stack a std::vector of Eigen matrices. Here is how I implemented a function which is more general purpose. Let me know if this can be further improved:
我有一个稍微不同的用例:垂直堆叠特征矩阵的 std::vector。这是我如何实现一个更通用的功能。让我知道这是否可以进一步改进:
// matrix_eig = Eigen::MatrixXf in RowMajor format
matrix_eig VStack(const std::vector<matrix_eig> &mat_vec) {
assert(!mat_vec.empty());
long num_cols = mat_vec[0].cols();
size_t num_rows = 0;
for (size_t mat_idx = 0; mat_idx < mat_vec.size(); ++mat_idx) {
assert(mat_vec[mat_idx].cols() == num_cols);
num_rows += mat_vec[mat_idx].rows();
}
matrix_eig vstacked_mat(num_rows, num_cols);
size_t row_offset = 0;
for (size_t mat_idx = 0; mat_idx < mat_vec.size(); ++mat_idx) {
long cur_rows = mat_vec[mat_idx].rows();
vstacked_mat.middleRows(row_offset, cur_rows) = mat_vec[mat_idx];
row_offset += cur_rows;
}
return vstacked_mat;
}
回答by thclark
I'd use Eigen's block indexingin a way similar to this post(which concatenates to an existing matrix).
我会以类似于这篇文章(连接到现有矩阵)的方式使用Eigen 的块索引。
The block indexing avoids the direction ambiguity in the accepted approach, and is pretty compact syntax. The following is equivalent to C = cat(2, A, B)
in MATLAB:
块索引避免了公认方法中的方向歧义,并且是非常紧凑的语法。以下相当于C = cat(2, A, B)
在 MATLAB 中:
MatrixXd C(A.rows(), A.cols()+B.cols());
C.leftCols(A.cols()) = A;
C.rightCols(B.cols()) = B;