CUDA thrust max_element with custom comparison function

I’m looking at thrusts’s max_element right now, and I would like to know how I can use a custom comparison function so that I can operate on structs :smile: . My struct looks something like this:

struct Particle {
    glm::vec3 Acceleration; // [float|float|float]
    glm::vec3 Velocity;     // [float|float|float]

And I would like to find the highest velocity magnitude in my array. This is how I calculate vm:

float timeStep = 0.01f;
float vm = glm::length2(particles[i].Velocity + particles[i].Acceleration * timeStep);

This is what I have so far, this just finds the highest float value:

const int N = 1000000;
float* h_vec = new float[N];
for (int i = 0; i < N; i++) {
    h_vec[i] = i;

float* d_vec;
COMPUTE_SAFE(cudaMalloc((void**)&d_vec, N * sizeof(float)));
COMPUTE_SAFE(cudaMemcpy(d_vec, h_vec, N * sizeof(float), cudaMemcpyHostToDevice));

thrust::device_ptr<float> dev_ptr = thrust::device_pointer_cast(d_vec);
thrust::device_ptr<float> min_ptr = thrust::max_element(dev_ptr, dev_ptr + N);

printf("\nMininum value = %f\n", min_ptr[0]);

Any advice would be greatly appreciated :smile:

Solved it by using a transform_reduce function

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.