2017-01-20 279 views
2

我在Eigen中有兩個稀疏矩陣,我想將它們垂直連接成一個。作爲一個例子代碼的目標將是:連續稀疏矩陣Eigen

SparseMatrix<double> matrix1; 
matrix1.resize(10, 10); 
SparseMatrix<double> matrix2; 
matrix2.resize(5, 10); 

SparseMatrix<double> MATRIX_JOIN; 
MATRIX_JOIN.resize(15, 10); 
MATRIX_JOIN << matrix1, matrix2; 

我發現一個forum一些解決方案,但是,我沒能實現它。

縱向連接矩陣的正確方法是什麼?

編輯

我的實現:

SparseMatrix<double> L; 
SparseMatrix<double> C; 
// ... (Operations with the matrices) 
SparseMatrix<double> EMATRIX; 
EMATRIX.resize(L.rows() + C.rows(), L.cols()); 
EMATRIX.middleRows(0, L.rows()) = L; 
EMATRIX.middleRows(L.rows(), C.rows()) = C; 

我得到的類型錯誤,acording編譯器的右手邊是一個徵::塊,左側是本徵::稀疏矩陣

+0

什麼是「我是不是能夠實現它。」意思? –

+0

@ Code-Apprentice我無法實現我在論壇中找到的解決方案。這也意味着加入(在論壇中的解決方案)一個稀疏和密集的矩陣 – Javier

+0

重複相同的單詞並不能解釋這些單詞的含義。請準確顯示您所做的事情以及編譯和運行您編寫的代碼時會發生的情況。 –

回答

3

據我所知,目前沒有內置的解決方案。您可以通過使用the internal insertBack function是方式比解決方案更有效:

SparseMatrix<double> M(L.rows() + C.rows(), L.cols()); 
M.reserve(L.nonZeros() + C.nonZeros()); 
for(Index c=0; c<L.cols(); ++c) 
{ 
    for(SparseMatrix<double>::InnerIterator itL(L, c); itL; ++itL) 
     M.insertBack(itL.row(), c) = itL.value(); 
    for(SparseMatrix<double>::InnerIterator itC(C, c); itC; ++itC) 
     M.insertBack(itC.row(), c) = itC.value(); 
} 
M.finalize(); 
+0

這比使用三元組更有效嗎? – Javier

+0

@Javier它應該是在所有,但非常奇怪的情況下。在許多情況下,這可能並不重要。 – chtz

1

最後我做了以下內容:

MATRIX_JOIN.resize(matrix1.rows() + matrix2.rows(), matrix1.cols() + matrix2.cols()); 
MATRIX_JOIN.setZero(); 

// Fill MATRIX_JOIN with triples from the other matrices 
std::vector<Triplet<double> > tripletList; 
for (int k = 0; k < matrix1.outerSize(); ++k) 
{ 
    for (SparseMatrix<double>::InnerIterator it(matrix1, k); it; ++it) 
    { 
     tripletList.push_back(Triplet<double>(it.row(), it.col(), it.value())); 
    } 
} 
for (int k = 0; k < matrix2.outerSize(); ++k) 
{ 
    for (SparseMatrix<double>::InnerIterator it(matrix2, k); it; ++it) 
    { 
     tripletList.push_back(Triplet<double>(it.row(), it.col(), it.value())); 
    } 
} 
FINALMATRIX.setFromTriplets(tripletList.begin(), tripletList.end()); 

可以通過調用tripleList.reserve(X)來加速,其中X是要插入的三元組的預期數量。