2013-03-18 39 views
0

我有一個程序,在數據讀出的格式來建立和訪問值:C++ - 使用升壓在稀疏矩陣

Row Column Value 
1  1   4 
1  3   5 
2  1   6 
... 

其中的前兩列指的是矩陣的索引,和值列包含存儲在矩陣中(行,列)座標處的值。

如果我實際上構造了一個2d數組來表示矩陣,它會非常大,因爲我的輸入數據非常稀疏。相反,我想要構建一個稀疏矩陣表示,它將允許我查找與(行,列)對相對應的值,如果不存在,則返回0。

似乎boost有辦法做到這一點,但我找不到足夠的文檔來真正理解如何使用它。

我已經通過這些深入閱讀,但我仍然不知道如何PROCEDE:

http://www.guwi17.de/ublas/doc/html/ex__fill1_8cpp-source.html http://www.boost.org/doc/libs/1_39_0/libs/numeric/ublas/doc/matrix_sparse.htm

我是C++新手,所以我不能確定如何使用升壓創建一個稀疏矩陣從我的輸入數據(假設我已經讀過)。我也沒有辦法找到如何使用boost稀疏矩陣實際返回與(行,列)對有關的值。任何人都可以向我指出一些基本的例子,或者解釋我可以如何做到這一點?

感謝您提供任何幫助。

回答

7

有幾種類型的稀疏矩陣實現在升壓:mapped_matrix(由關聯容器如std::map支持),compressed_matrixcoordinate_matrix(由可調整大小的陣列支持)。所有這些用法都是一樣的。

下面是壓縮矩陣的一些基礎知識:

#include <iostream> 
#include <sstream> 
#include <boost/numeric/ublas/matrix_sparse.hpp> 

namespace ublas = boost::numeric::ublas; 
int main() 
{ 
    ublas::compressed_matrix<int> m(10, 10); // 10x10 compressed matrix 

    // replace by ifstream in("filename") in real code 
    std::istringstream in("1  1   4\n" 
          "1  3   5\n" 
          "2  1   6\n"); 

    // read from stream 
    int val; 
    for(size_t r,c; in >> r >> c >> val;) 
     m(r,c) = val; 

    // print out 
    for(size_t i = 0; i < m.size1(); ++i) 
    { 
     for(size_t j = 0; j < m.size2(); ++j) 
      std::cout << m(i,j) << ' '; 
     std::cout << '\n'; 
    } 

    // info on the storage 
    std::cout << "Non-zeroes: " << m.nnz() << '\n' 
       << "Allocated storage for " << m.nnz_capacity() << '\n'; 

} 

在線演示:http://liveworkspace.org/code/2iCZuF