quant
quant

Reputation: 23052

How do I sum all elements in a ublas matrix?

According to this page there should be a sum function provided in ublas, but I can't get the following to compile:

boost::numeric::ublas::matrix<double> mymatrix;
std::cout << boost::numeric::ublas::sum(mymatrix);

error is:

testcpp:146:144: error: no matching function for call to ‘sum(boost::numeric::ublas::matrix&)’

I'm #includeing:

#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/matrix_proxy.hpp>

Am I missing an include, or did I misunderstand the docs? How would I achieve this (I'm trying to sum up all elements of a matrix and produce a single double)?

Upvotes: 2

Views: 2569

Answers (1)

Cubbi
Cubbi

Reputation: 47428

As pointed out in comments, sum only applies to vectors (see documentation)

You could certainly get at m.data() and sum the values that way, but you are using a linear algebra library! Multiply a row vector of 1's by your matrix, and sum the result:

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

namespace bls = boost::numeric::ublas;
int main()
{
    bls::matrix<double> m(3, 3);
    for (unsigned i = 0; i < m.size1(); ++i)
        for (unsigned j = 0; j < m.size2(); ++j)
            m(i, j) = 3 * i + j;

   std::cout << "Sum of all elements of " << m << " is "
             << sum(prod(bls::scalar_vector<double>(m.size1()), m)) << '\n';
}

A more reusable approach would be to define a sum that takes a matrix_expression, as the shark library did.

Upvotes: 2

Related Questions