在特征中,我们可以使用其他矩阵或 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/