2
votes

I am trying to compute square root of all elements of a Boost Ublas matrix. So far, I have this, and it works.

#include <iostream>
#include "boost\numeric\ublas\matrix.hpp"
#include <Windows.h>
#include <math.h>
#include <cmath>
#include <algorithm>
typedef boost::numeric::ublas::matrix<float> matrix;
const size_t X_SIZE = 10;
const size_t Y_SIZE = 10;
void UblasExpr();


int main()
{
    UblasExpr();
    return 0;
}

void UblasExpr()
{
    matrix m1, m2, m3;
    m1.resize(X_SIZE, Y_SIZE);
    m2.resize(X_SIZE, Y_SIZE);
    m3.resize(X_SIZE, Y_SIZE);

    for (int i = 0; i < X_SIZE; i++)
    {
        for (int j = 0; j < Y_SIZE; j++)
        {
            m1(i, j) = 2;
            m2(i, j) = 10;
        }
    }

    m3 = element_prod(m1, m2);
    std::transform(m1.data().begin(), m1.data().end(), m3.data().begin(), std::sqrtf);
    for (int i = 0; i < X_SIZE; i++)
    {
        for (int j = 0; j < Y_SIZE; j++)
        {
            std::cout << m3(i, j) << "   ";
        }
        std::cout << std::endl;
    }
}

But, I would like to not use the std::transform, and instead do something like this : m3 = sqrtf(m1);

Is there a way to make it work? My application is very performance sensitive, so the alternative is only acceptable if it results in no loss of efficiency.

P.S. I would like to do this for a whole lot of other operations like log10f, cos, acos, sin, asin, pow. I need these all in my code.

1
why don't you like std::transform?TemplateRex

1 Answers

3
votes

You can define your own sqrt function with an appropriate signature:

typedef boost::numeric::ublas::matrix<float> matrix;
matrix sqrt_element(const matrix& a)
{
   matrix result(a.size1(), a.size2());
   std::transform(a.data().begin(), a.data().end(), result.data().begin(), std::sqrtf);
   return result;
}

You could also define a general 'apply_elementwise' to take a callable object as an argument (untested/not compiled):

typedef boost::numeric::ublas::matrix<float> matrix;

template <typename CALLABLE>
matrix apply_elementwise(const CALLABLE& f, const matrix& a)
{
   matrix result(a.size1(), a.size2());
   std::transform(a.data().begin(), a.data().end(), result.data().begin(), f);
   return result;
}

Then you could call this as:

matrix y(apply_elementwise(std::sqrt, x));
matrix z;
z = apply_elementwise(std::cos,  x);

In these functions, we're returning a matrix by value. Ideally, you want to make sure you that the matrix class you're using employs rvalue-reference constructors and assignment operators to minimize copying of data.