简体   繁体   English

本征库::如何从现有的稀疏矩阵中创建块对角稀疏矩阵?

[英]Eigen Library:: How do I create a block diagonal sparse matrix out of existing sparse matrices?

I have a bunch of (n*n) sized sparse matrices called M1, M2... , Mj. 我有一堆(n * n)大小的稀疏矩阵,称为M1,M2 ...,Mj。

I want to create a large block-diagonal sparse matrix that looks like this: 我想创建一个大的块对角稀疏矩阵,如下所示:

    |M1 0  0 . . . |
    |0  M2 0 . . . |
    |.  .  . . . . |
    |.  .  . Mj-1 0|
    |0  0  0 ... Mj|

I tried the following: 我尝试了以下方法:

    Eigen::SparseMatrix<double> MatBLK(j*n,j*n);
    MatBLK.reserve(Eigen::VectorXd::Constant(j*n,3); 
    //I know that there are at most 3 nonzero elements per row

    MatBLK.topLeftCorner(n,n) = M1.topLeftCorner(n,n);
    MatBLK.block(n,n,n,n) = M2.topLeftCorner(n,n);
    .
    .
    MatBLK(bottomRightCorner(n,n)) = Mj.topLeftCorner(n,n);
    MatBLK.makeCompressed();

This method is not working. 此方法无效。 The values in the smaller matrices aren't getting copied to the larger Block Matrix. 较小矩阵中的值不会复制到较大的块矩阵中。 The function: 功能:

    MatBLK.nonZeros() 

returns 0. 返回0。

I am new to this library. 我是这个图书馆的新手。 Any help would be greatly appreciated. 任何帮助将不胜感激。

Unfortunately it looks like you can't assign sparse matrices in that way due to how inefficient the resulting code would be. 不幸的是,由于生成的代码效率低下,因此您似乎无法以这种方式分配稀疏矩阵。 This forum post is almost 2 years old but it seems things are still the same ( https://forum.kde.org/viewtopic.php?f=74&t=112018 ) 这个论坛帖子已经有将近2年的历史了,但是看起来事情还是一样的( https://forum.kde.org/viewtopic.php?f=74&t=112018

You have to assign entries one by one, either with direct assignment or triplets. 您必须使用直接分配或三元组一个接一个地分配条目。

A.block(i,j,m,n) = B;

becomes

for (int ii = i; ii < i+m; ++ii) {
  for (int jj = j; jj < j+n; ++jj) {
    // direct assignment 
    A.insert(ii, jj) = B(ii - i, jj - j);

    // triplets
    triplets.push_back(Triplet(ii, jj, B(ii-i,jj-j)));
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM