c++ - 特征:如何用一些子稀疏矩阵初始化稀疏矩阵

标签 c++ sparse-matrix eigen

在特征中,我们可以使用其他矩阵或 vector 来初始化矩阵或 vector ,如下所示:

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 有像这样的内置初始化程序吗?或者我需要自己写,如果可以的话?怎么办?

最佳答案

由于存储格式的原因,您不能拥有这样的初始值设定项。来自手册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;
}

关于c++ - 特征:如何用一些子稀疏矩阵初始化稀疏矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43532391/

相关文章:

java - 我可以使用什么库在 Java 或 Scala 中计算大型稀疏矩阵?

c++ - MATLAB 中具有稀疏功能的任何 C++/C 等效函数

c++ - 如何确定矩阵在 Eigen 中是否可逆(正则、非奇异、满秩……)?

c++ - VS2010 分析器/泄漏检测

c++ - 我可以从包含一个类的多个对象的列表中得到一些东西吗?

c++ - 是否可以非法更改 CLASS 的 PRIVATE 数据成员?

c++ - SimplicialLLT 返回错误的 cholesky 因素

c++ - 如何将C++写入速度加速到CrystalDiskMark测试的速度?

python - 非常大和非常稀疏的非负矩阵分解

optimization - Eigen :就位系数乘法