2017-04-21 210 views
-1

在本徵,我們可以初始化與其他一些矩陣或矢量這樣的矩陣或向量:徵:如何初始化一個稀疏矩陣與一些子稀疏矩陣

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 

,但它並不適用於稀疏矩陣工作, 本徵有內置初始化器嗎?或者我需要自己寫,如果是的話?怎麼樣?

+0

爲了記錄,我填寫了一項功能請求:http://eigen.tuxfamily.org/bz/show_bug.cgi?id=1420。這絕對是一個有用的功能。 – ggael

回答

1

由於存儲格式,您不能擁有這樣的初始化程序。從手動Sparse matrix manipulations > Block operations

然而,由於性能的原因,寫入到子稀疏矩陣是有限得多,並且目前僅鄰接套列的列優先(相應的(相應的行。)。行 - 主)SparseMatrix是可寫的。而且,這些信息必須在編譯時知道,而忽略了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; 
}