C ++ Eigen:如何动态连接矩阵(指针问题?) [英] C++ Eigen: How to concatenate matrices dynamically (pointer issue?)
问题描述
我有以下问题: 我有几个部分(本征)的MatrixXds,我想连接到另一个更大的,仅作为指针的MatrixXd变量.但是,较小矩阵的大小及其数量都是动态的,因此我不能使用<<<轻松操作.
I have the following problem: I have several partial (eigen) MatrixXds I want to concatenate to another, larger, MatrixXd variable I only have as a pointer. However, both the size of the smaller matrices and their number are dynamic, so I cannot use the << operator easily.
因此,我尝试使用Eigen的MatrixXd块函数,尝试以下操作(较小的矩阵显然存储在list_subdiagrams中,而base-> cols()定义矩阵的数目):
So I'm trying the following (the smaller matrices are stored in list_subdiagrams, obviously, and basis->cols() defines the number of matrices), using Eigen's MatrixXd block funtionality:
// sd[] contains the smaller matrices to be concatenated; all are of the same size
// col defines the total number of smaller matrices
MatrixXd* ret = new MatrixXd(sd[0]->rows(), col*sd[0]->cols());
for (int i=0; i<col; ++i){
ret->block(0, i*sd[0]->cols(), sd[0]->rows(), sd[0]->cols()) = *(sd[i]);
}
不幸的是,这似乎以某种方式覆盖了* ret变量的一部分-因为在通过块分配之前,大小(在我的测试用例中)正确显示为2x1.分配后变成140736006011136x140736006011376 ...
This, unfortunately, appears to somehow overwrite some part of the *ret variable - for before the assignment via the block, the size is (in my test-case) correctly shown as being 2x1. After the assignment it becomes 140736006011136x140736006011376 ...
谢谢您的帮助!
推荐答案
您不知道尺寸是什么意思?您可以使用成员函数cols()/rows()
来获取大小.另外,我假设通过串联表示直接和?在这种情况下,您可以执行类似的操作
What do you mean you don't know the size? You can use the member functions cols()/rows()
to get the size. Also, I assume by concatenation you mean direct sum? In that case, you can do something like
#include <iostream>
#include <Eigen/Dense>
int main()
{
Eigen::MatrixXd *A = new Eigen::MatrixXd(2, 2);
Eigen::MatrixXd *B = new Eigen::MatrixXd(3, 3);
*A << 1, 2, 3, 4;
*B << 5, 6, 7, 8, 9, 10, 11, 12, 13;
Eigen::MatrixXd *result = new Eigen::MatrixXd(A->rows() + B->rows(), A->cols() + B->cols());
result->Zero(A->rows() + B->rows(), A->cols() + B->cols());
result->block(0, 0, A->rows(), A->cols()) = *A;
result->block(A->rows(), A->cols(), B->rows(), B->cols()) = *B;
std::cout << *result << std::endl;
delete A;
delete B;
delete result;
}
因此,首先确保它适用于2个矩阵,对其进行测试,然后将其扩展到N
.
So first make sure it works for 2 matrices, test it, then extend it to N
.
这篇关于C ++ Eigen:如何动态连接矩阵(指针问题?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!