特征:如何用子稀疏矩阵初始化稀疏矩阵 [英] Eigen: How to initialize a sparse matrix with some sub sparse matrix

查看:55
本文介绍了特征:如何用子稀疏矩阵初始化稀疏矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在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有像这样的内置初始值设定项吗?或者我需要自己写,如果是这样的话?如何?

推荐答案

由于存储格式的原因,您不能拥有这样的初始值设定项。摘自手册Sparse matrix manipulations > Block operations

然而,出于性能原因,写入子稀疏矩阵要有限得多,目前仅连续的列集(分别为行)列为主(分别为行较多)SparseMatrix是可写的。此外,此信息必须在编译时知道,省略了块(...)等方法。和角*(...)。

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

#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;
}

这篇关于特征:如何用子稀疏矩阵初始化稀疏矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆