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

在CUDA中查找大于阈值的索引和值,cuda,Cuda,我有一个矩阵,我想找到大于阈值的索引和值,那么如何使用CUDA呢?或者,这是将矩阵复制到内存并让cpu完成工作的更好方法?您可以非常轻松地使用它来实现这一点,它为您提供了所需的基本构建块。下面的代码首先查找满足条件值>阈值的索引,然后提取相应的值。如果您不需要索引,您可以一步完成所有这一切 #include <thrust/gather.h> #include <thrust/iterator/counting_iterator.h> #include <thrus

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

您可以非常轻松地使用它来实现这一点,它为您提供了所需的基本构建块。下面的代码首先查找满足条件值>阈值的索引,然后提取相应的值。如果您不需要索引,您可以一步完成所有这一切

#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;
}

实际上,有一个内置函数可以直接执行此操作:

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


谢谢你的否决票,我可能不会再尝试回答问题了

我想知道是否有更好的方法,我还没有找到比什么更好的方法?你还没有解释你现在正在使用或尝试做什么。如果你不知道我在尝试什么,请再阅读问题,谢谢什么样的矩阵?1D,2D?如何线性地存储它们?它是二维矩阵,线性地存储,但这有关系吗?请解释一下这行:推力::设备向量::迭代器结束@究竟什么是不清楚的?正如我在回答中所写的那样,这会找到满足条件值>阈值的索引,只有当序列被排序时,这些索引才会满足这个问题。幸运的是,您已经介绍了排序。[
indices: 91 92 93 94 95 96 97 98 99 
values: 91 92 93 94 95 96 97 98 99