2017-02-21 8 views
3

저는 Cigen에서 Eigen의 희소 행렬로 작업하고 있습니다. 정기적 인 고유 행렬처럼 특정 행과 열 인덱스에 저장된 데이터를 읽으 려합니다.C++ Eigen 스파 스 매트릭스에서 특정 (행, 열) 색인에 액세스하는 방법?

std::vector<Eigen::Triplet<double>> tripletList; 

// TODO: populate triplet list with non-zero entries of matrix 

Eigen::SparseMatrix<double> matrix(nRows, nCols); 
matrix.setFromTriplets(tripletList.begin(), tripletList.end()); 

// TODO: set iRow and iCol to be valid indices. 

// How to read the value at a specific row and column index? 
// double value = matrix(iRow, iCol); // Compiler error 

이 색인 생성 작업을 수행하려면 어떻게해야합니까?

+0

한 가지 가능한 해결책은 스파 스 매트릭스 ('Eigen :: MatrixXd dense = Eigen :: MatrixXd (스파 스);)에서 조밀 한 매트릭스를 만드는 것이지만, 이는 많은 계산 비용을 가지며 대부분의 어플리케이션에서 바람직하지 않습니다 . – MattKelly

답변

7

coeff을 시도해보십시오

double value = matrix.coeff(iRow, iCol); 

을 당신이 const가 아닌 버전을 사용 coeffRef을 대신합니다. 요소가없는 경우 coeffRef을 사용하면 요소가 삽입됩니다.

+0

정확히 내가 뭘 찾고 있었는지 - 고마워! – MattKelly

+0

문서 : https://eigen.tuxfamily.org/dox/classEigen_1_1SparseMatrix.html#ad2c8bc92696f39d53c5e598a50e58f68 – MattKelly

0

나 여기

for (int i=0; i<matrix.rows(); ++i){ 
     cout << " i,j=" << i << "," << j << " value=" << matrix.coeff(i,j) << std::endl; 
} 
0

에 대한이 코드 작품은 원시의 방법으로 할 수 있습니다 : 당신이 원하는

방법은 innerIndexPtr, outerIndexPtr, InnerNNZsvaluePtr이다.

struct sparseIndex { 
    std::size_t row, col; 
    template<class SparseMatrix, class Scalar=typename SparseMatrix::Scalar> 
    Scalar get_from(SparseMatrix const& m, Scalar def={}) const { 
    if ((std::size_t)m.cols() >= col) return def; 
    auto* inner_index_start = m.innerIndexPtr()+m.outerIndexPtr()[col]; 
    auto* inner_index_end = inner_index_start; 
    if (auto* nzp = m.innerNonZeroPtr()) { // returns null if compressed 
     inner_index_end += nzp[col]; 
    } else { 
     inner_index_end = m.innerIndexPtr()+m.outerIndexPtr()[col+1]; 
    } 
    auto search_result = std::equal_range(
     inner_index_start, 
     inner_index_end, 
     (typename SparseMatrix::StorageIndex)row 
    ); 
    if (search_result.first == search_result.second) return def; 
    if ((std::size_t)*search_result.first != row) return def; 
    return m.valuePtr()[search_result.first-m.innerIndexPtr()]; 
    } 
};  

사용 :

auto r = sparseIndex{2,2}.get_from(sparseMatrix); 

코드 테스트하지. 세부 사항에 동의하지 않는 these docsthese docs을 기반으로합니다.

나는 단지 012im을 보았다고 생각한다. .coeff, 소금 한 알과 함께 이것을 가져라. :)