本征:如何用一些子稀疏矩阵初始化稀疏矩阵

Eigen: How to initialize a sparse matrix with some sub sparse matrix

在 eigen 中,我们可以像这样用其他矩阵或向量初始化一个矩阵或向量:

MatrixXf matA(2, 2);
matA << 1, 2, 3, 4;
MatrixXf matB(4, 4);
matB << matA, matA/10, matA/10, matA;
std::cout << matB << std::endl;

我想达到的目标:

SparseMatrix<double> matA(2, 2);
matA.coeffRef(0, 0) = 1;
matA.coeffRef(1, 1) = 1;
SparseMatrix<double> matB(4, 4);
matB << matA, matA/10, matA/10, matA;
std::cout << matB << std::endl;

然后我得到一个这样的矩阵:

1   0   0.1 0
0   1   0   0.1
0.1 0   1   0
0   0.1 0   0.1

但是,它不适用于稀疏矩阵, 那么本征有这样的内置初始化器吗?或者我需要自己写,如果是这样?怎么样?

由于存储格式的原因,您不能拥有这样的初始化程序。来自手册 Sparse matrix manipulations > Block operations:

However, for performance reasons, writing to a sub-sparse-matrix is much more limited, and currently only contiguous sets of columns (resp. rows) of a column-major (resp. row-major) SparseMatrix are writable. Moreover, this information has to be known at compile-time, leaving out methods such as block(...) and corner*(...).

您唯一的选择是将所有内容都转换为密集矩阵,使用逗号初始值设定项并转换回稀疏矩阵。

#include <iostream>
#include <Eigen/Sparse>

using namespace Eigen;
typedef SparseMatrix<double> SparseMatrixXd;

int main()
{
  SparseMatrixXd matA(2, 2);
  matA.coeffRef(0, 0) = 1;
  matA.coeffRef(1, 1) = 1;
  SparseMatrixXd matB(4, 4);
  MatrixXd matC(4,4);
  matC <<
    MatrixXd(matA),
    MatrixXd(matA)/10,
    MatrixXd(matA)/10,
    MatrixXd(matA);
  matB = matC.sparseView();
  std::cout << matB << std::endl;
}

或者,对于这个具体示例,您可以使用不受支持的 Kronecker 产品模块。

#include <iostream>
#include <Eigen/Sparse>
#include <unsupported/Eigen/KroneckerProduct>

using namespace Eigen;
typedef SparseMatrix<double> SparseMatrixXd;

int main()
{
  SparseMatrixXd matA(2, 2);
  matA.coeffRef(0, 0) = 1;
  matA.coeffRef(1, 1) = 1;
  SparseMatrixXd matB(4, 4);
  matB =
    kroneckerProduct( (MatrixXd(2,2) << 1,0,0,1).finished(), matA ) +
    kroneckerProduct( (MatrixXd(2,2) << 0,1,1,0).finished(), matA/10);
  std::cout << matB << std::endl;
}