Search code examples
cudaaveragethrust

how to calculate an average from a int2 array using Thrust


I'm trying to calculate the average of a certain array which contains points (x,y).
is it possible to use thrust to find the average point represented as a (x,y) point? i could also represent the array as a thrust::device_vector<int>when each cell contains the absolute position of the point, meaning i*numColumns + j though I'm not sure that the average number represents the average cell.
Thanks!


Solution

  • #include <iostream>
    #include <thrust/device_vector.h>
    #include <thrust/reduce.h>
    
    struct add_int2 {
      __device__
      int2 operator()(const int2& a, const int2& b) const {
        int2 r;
        r.x = a.x + b.x;
        r.y = a.y + b.y;
        return r;
      }
    };
    
    #define N 20
    
    int main()
    {
      thrust::host_vector<int2> a(N);
      for (unsigned i=0; i<N; ++i) {
        a[i].x = i;
        a[i].y = i+1;
      }
    
      thrust::device_vector<int2> b = a;
    
      int2 init;
      init.x = init.y = 0;
    
      int2 ave = thrust::reduce(b.begin(), b.end(), init, add_int2());
      ave.x /= N;
      ave.y /= N;
    
      std::cout << ave.x << " " << ave.y << std::endl;
      return 0;
    }