特征:如何使用一些子稀疏矩阵

时间:2017-04-21 01:23:26

标签: c++ 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

但是,它对稀疏矩阵不起作用, 那么eigen有这样的内置初始化器吗?或者我需要自己写,如果是这样的话?如何?

1 个答案:

答案 0 :(得分:1)

由于存储格式,您无法拥有此类初始化程序。从手册Sparse matrix manipulations > Block operations

  

然而,出于性能原因,写入子稀疏矩阵更加有限,并且目前只有列主要(resp.行主要)SparseMatrix的连续列(resp。行)是可写的。此外,必须在编译时知道此信息,省略诸如块(...)和角*(...)之类的方法。

您唯一的选择是将所有内容转换为密集矩阵,使用逗号初始化程序并转换回稀疏。

#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;
}
相关问题