[Home]Examples - How To Extend UBLAS

BOOST WIKI | RecentChanges | Preferences | Page List | Links List

Showing revision 2
Back to Effective UBLAS

Example 1 - "Vectorize" standard math functions

Q: Did you ever want to apply a simple function to all elements of a vector or a matrix? Usually this means iteration over all elements. But is there a better way? Can we hide the loops and even use lazy computation?

A: Yes, we can.

Example: We want to apply log() to all elements of a vector.

The logarithm is a unary function, so we have to look for vector_unary. This is already implemented for the unary minus and the complex conjugate of a vector. In order to have a flexible notation we want to create a new function similar to conj() that returns a vector expression applying a (at compile time) known functor to any element of a vector. Therefore we copy the unary minus from vector_expression.hpp and modify some types.

  // (op v) [i] = op( v [i] )
  template<class OP, class E> 
  BOOST_UBLAS_INLINE
  typename vector_unary_traits<E, OP>::result_type
  apply_to_all (const vector_expression<E> &e, const OP& op = OP() ) {
    typedef typename vector_unary_traits<E, OP>::expression_type expression_type;
    return expression_type (e ());
  }

Now we are able to write apply_to_all(v, op) where op can be any functor with following structure:

namespace functor {

  template <class T>
  class log
  {
  public:
    typedef T value_type;
    typedef T result_type;
    log() { }
    
    static
    result_type apply(const value_type& x)
    {
      return std::log(x); // insert any function you want
    }

  };

}

All done. The usage is very simple:

  vector<double> v( 100 );
  // ... fill v ...                                     
  std::cout << apply_to_all( v, functor::log<double>() ) << std::endl; 
  std::cout << apply_to_all<functor::log<double> >( v ) << std::endl; 


BOOST WIKI | RecentChanges | Preferences | Page List | Links List
Edit revision 2 of this page | View other revisions | View current revision
Edited May 23, 2006 1:52 am (diff)
Search:
Disclaimer: This site not officially maintained by Boost Developers