在CUDA中查找大于阈值的索引和值

时间:2015-04-24 12:02:21

标签: cuda

我有一个矩阵,我想找到大于阈值的索引和值,那么如何使用CUDA呢?或者它是将矩阵复制到内存并让cpu完成工作的更好方法吗?

2 个答案:

答案 0 :(得分:0)

您可以使用Thrust轻松实现此功能,它为您提供所需的基本构建块。以下代码首先查找满足条件(value > threshold)的索引,然后提取相应的值。如果您不需要索引,则可以一步完成所有这些操作。

#include <thrust/gather.h>
#include <thrust/iterator/counting_iterator.h>
#include <thrust/iterator/permutation_iterator.h>
#include <thrust/functional.h>
#include <thrust/copy.h>
#include <thrust/device_vector.h>
#include <iostream>
#include <thrust/sequence.h>

int main()
{
  const int N = 100;
  int threshold = 90;

  thrust::device_vector<int> data(N);
  // fill with demo data
  thrust::sequence(data.begin(), data.end());

  // find out the indices
  thrust::device_vector<int> indices(N);
  thrust::device_vector<int>::iterator end = thrust::copy_if(thrust::make_counting_iterator(0),
                                                             thrust::make_counting_iterator(N),
                                                             data.begin(),
                                                             indices.begin(), 
                                                             thrust::placeholders::_1 > threshold);
  int size = end-indices.begin();
  indices.resize(size);

  // fetch corresponding values
  thrust::device_vector<int> values(size);
  thrust::copy(thrust::make_permutation_iterator(data.begin(), indices.begin()),
               thrust::make_permutation_iterator(data.end(), indices.end()),
               values.begin());

  std::cout << "indices: ";
  thrust::copy(indices.begin(), indices.end(), std::ostream_iterator<int>(std::cout, " "));
  std::cout << std::endl;

  std::cout << "values: ";
  thrust::copy(values.begin(), values.end(), std::ostream_iterator<int>(std::cout, " "));
  std::cout << std::endl;

  return 0;
}

该演示程序的输出是:

indices: 91 92 93 94 95 96 97 98 99 
values: 91 92 93 94 95 96 97 98 99 

答案 1 :(得分:-1)

实际上,有一个内置函数可以做到这一点:

ForwardIterator thrust::lower_bound (ForwardIterator first, ForwardIterator last, const LessThanComparable& value)

它将迭代器返回到第一个元素,可以在其中保留值的同时保持列表的顺序。因此,如果value是您的阈值,它将迭代器返回到阈值> = i的第一个元素i。

谢谢你的投票,我可能不会再尝试回答一个问题。

相关问题