Search code examples
c++boost-ublas

How to insert an element into ublas matrix with dynamic size


Run time error while trying to insert element in a matrix with size not specified initially.

The below code runs finr for m1 but throws error for m2.

#include <iostream>
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/io.hpp>    

int main () {
    boost::numeric::ublas::matrix<double> m1 (1,1);
    boost::numeric::ublas::matrix<double> m2;
    unsigned int i = 0;
    m1(i,i)=9;  // This works completely
    m2(i,i)=9;  // This one throws error
    return 0;
}

If someone can provide an alternative to achieve this, i shall be highly grateful.


Solution

  • As you have noticed yourself, boost::numeric::ublas::matrix doesn't resize itself automatically, like std::vector. You have to do the resizing manually before calling operator(), or write a function template that does the resizing for you as shown here:

    namespace ublas = boost::numeric::ublas; //just a friendly alias!
    
    template<typename T, typename U>
    void assign(ublas::matrix<T>& m,std::size_t r,std::size_t c,U const& data)
    {
        m.resize(std::max(m.size1(), r+1), std::max(m.size2(), c+1));
        m(r, c) = data;
    }
    

    Now you can do this:

    int main () 
    {
        ublas::matrix<double> m;
    
        assign(m, 0, 0, 9);  //m(0,0) = 9; 
        assign(m, 3, 2, 20); //m(3,2) = 20
    
        std::cout << m << std::endl; //prints: [4,3]((9,0,0),(0,0,0),(0,0,0),(0,0,20))
        return 0;
    }
    

    Online demo

    Hope that helps.