user1764386
user1764386

Reputation: 5611

c++ - use boost to build and access values in a sparse matrix

I have a program that is reading in data in the format:

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

where the first two columns refer to the indices of a matrix, and the value column contains the value stored at that (row, column) coordinate in a matrix.

If I was to actually construct a 2d array to represent the matrix, it would be very large since my input data is very sparse. Instead I want to build a sparse matrix representation that will allow me to look up the value corresponding to a (row, column) pair, returning 0 if it is not present.

It seems like boost has a way to do this, but I can not find enough documentation to actually understand how to use it.

I have read through these in depth, but am still not sure how to 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

I am a c++ newbie so am unsure of how to use boost to create a sparse matrix from my input data (assuming I already read it in). I also am having no luck finidng out how to actually return the value pertaining to a (row, column) pair using a boost sparse matrix. Can anybody point me to some basic examples, or explain how I might do this?

Thank you for any help you can provide.

Upvotes: 1

Views: 3440

Answers (1)

Cubbi
Cubbi

Reputation: 47428

There are several kinds of sparse matrix implementations in boost: mapped_matrix (backed by an associative container such as std::map), compressed_matrix and coordinate_matrix (backed by resizeable arrays). Usage is the same for all of them.

Here's some basics for compressed 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';

}

online demo: http://liveworkspace.org/code/2iCZuF

Upvotes: 9

Related Questions