2
votes

How can I map a function to every element of a vector in uBLAS (like Map[] in Mathematica)?

For example; I want to take the sin() of all the elements of a uBLAS vector. Is there an optimized way in Boost, GSL, or any other numerical libraries to do this instead of simply looping through the elements of the vector?

Also, how would I perform other advanced operations on the uBLAS vectors such as rotating, deleting duplicates, or padding with zeros, etc?

2
It's a refinement of the vector expression syntax, so it still supports begin(), end() etc. You can still use the standard algorithms. boost.org/doc/libs/1_47_0/libs/numeric/ublas/doc/… - Seb Holzapfel

2 Answers

1
votes

Your vector (according to this) supports normal vector operations, just use the standard algorithms. In your case, here are a few of help (all inside <algorithm>):

  • For the sine operation, use std::transform with sinef from <cmath>
  • For rotation, (i'm assuming vector rotation, not angular rotation) std::rotate.
  • Deleting duplicates, use std::unique after a sort, deleting the unused elements.
  • Padding with zeros is more of an output operation - you don't perform that on a vector
1
votes

The closest equivalent to map is std::transform

#include <algorithm>
#include <functional>
#include <vector>
#include <cmath>

int main() {
   std::vector<float> values;
   values.push_back(0.5f);
   values.push_back(1.0f);
   std::transform(values.begin(), values.end(), values.begin(), std::ptr_fun(sinf));
}

And for de-duplication:

#include <algorithm>
#include <vector>
#include <iostream>
#include <iterator>

int main() {
   std::vector<int> duplicates;
   duplicates.push_back(1);
   duplicates.push_back(3);
   duplicates.push_back(5);
   duplicates.push_back(1);
   std::sort(duplicates.begin(), duplicates.end());
   duplicates.erase(std::unique(duplicates.begin(), duplicates.end()), duplicates.end());
   std::copy(duplicates.begin(), duplicates.end(), std::ostream_iterator<int>(std::cout, "\n"));
}

(I believe ublas vector has begin() and end() or similar)