Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the maximum element value AND its position using CUDA Thrust

Tags:

cuda

thrust

How do I get not only the value but also the position of the maximum (minimum) element (res.val and res.pos)?

thrust::host_vector<float> h_vec(100);
thrust::generate(h_vec.begin(), h_vec.end(), rand);
thrust::device_vector<float> d_vec = h_vec;

T res = -1;
res = thrust::reduce(d_vec.begin(), d_vec.end(), res, thrust::maximum<T>());
like image 686
rych Avatar asked Oct 10 '11 06:10

rych


1 Answers

Don't use thrust::reduce. Use thrust::max_element (thrust::min_element) in thrust/extrema.h:

thrust::host_vector<float> h_vec(100);
thrust::generate(h_vec.begin(), h_vec.end(), rand);
thrust::device_vector<float> d_vec = h_vec;

thrust::device_vector<float>::iterator iter =
  thrust::max_element(d_vec.begin(), d_vec.end());

unsigned int position = iter - d_vec.begin();
float max_val = *iter;

std::cout << "The maximum value is " << max_val << " at position " << position << std::endl;

Be careful when passing an empty range to max_element -- you won't be able to safely dereference the result.

like image 92
Jared Hoberock Avatar answered Oct 09 '22 07:10

Jared Hoberock