【问题标题】:Eigen: How to initialize a sparse matrix with some sub sparse matrixEigen:如何用一些子稀疏矩阵初始化稀疏矩阵
【发布时间】:2017-04-21 01:23:26
【问题描述】:

在 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

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

【问题讨论】:

标签: c++ sparse-matrix eigen


【解决方案1】:

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

但是,出于性能原因,写入子稀疏矩阵的限制要大得多,目前只有列优先(相应的行优先)稀疏矩阵的连续列集(相应的行)是可写的。此外,这些信息必须在编译时就知道,省略诸如 block(...) 和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;
}

【讨论】:

    猜你喜欢
    • 2023-03-16
    • 1970-01-01
    • 2018-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多