Определить значения, превышающие пороговое значение в массиве, и сохранить результат в двоичном (1/0) массиве с помощью команды thrust - PullRequest
0 голосов
/ 20 ноября 2018

Учитывая входной массив и порог, мне нужно создать выходной двоичный массив с 1 для значений больше порога и 0 для значений меньше порога.Мне нужно использовать тягу.

Моя попытка, как показано ниже, решает проблему, но выглядит очень неуклюже. Как это сделать за один шаг.Моя цель - сделать это за минимальное время вычислений.

#include <thrust/replace.h>
#include <thrust/execution_policy.h>
#include <thrust/fill.h>
#include <thrust/device_vector.h>

int main(int argc, char * argv[])
{
int threshold=1;
thrust::device_vector<int> S(6);
S[0] = 1;
S[1] = 2;
S[2] = 3;
S[3] = 4;
S[4] = 5;
S[5] = 6;

// fill vector with zeros
thrust::device_vector<int> A(6);
thrust::fill(thrust::device, A.begin(), A.end(), 0);

// detect indices with values greater than zero
thrust::device_vector<int> indices(6);
thrust::device_vector<int>::iterator end = thrust::copy_if(thrust::make_counting_iterator(0),thrust::make_counting_iterator(6),S.begin(),indices.begin(),                                                              thrust::placeholders::_1 > threshold);
int size = end-indices.begin();
indices.resize(size);

// use permutation iterator along with indices above to change to ones

thrust::replace(thrust::device,thrust::make_permutation_iterator(A.begin(), indices.begin()), thrust::make_permutation_iterator(A.begin(), indices.end()), 0, 1);

for (int i=0;i<6;i++)
{
std::cout << "A["<<i<<"]=" << A[i] << std::endl;
}

return 0;
}

Часть определения индексов взята из этого вопроса Stackoverflow

1 Ответ

0 голосов
/ 21 ноября 2018

Требуемые функциональные возможности могут быть достигнуты одним вызовом thrust::transform с пользовательским функтором сравнения. Вот пример указанного подхода.

#include <thrust/execution_policy.h>
#include <thrust/device_vector.h>
#include <thrust/transform.h>    

template<class T>
struct thresher
{
    T _thresh;
    thresher(T thresh) : _thresh(thresh) { }

    __host__ __device__ int operator()(T &x) const
    {
        return int(x > _thresh);
    }
};

int main(int argc, char * argv[])
{
    int threshold = 1;
    thrust::device_vector<int> S(6);
    S[0] = 1;
    S[1] = 2;
    S[2] = 3;
    S[3] = 4;
    S[4] = 5;
    S[5] = 6;

    thrust::device_vector<int> A(6);
    thrust::transform(S.begin(), S.end(), A.begin(), thresher<int>(threshold));

    for (int i=0;i<6;i++)
    {
        std::cout << "A["<<i<<"]=" << A[i] << std::endl;
    }

    return 0;
}
...