查找大于CUDA中阈值的索引和值 [英] Find the indices and values that larger than a threshold in CUDA

查看:219
本文介绍了查找大于CUDA中阈值的索引和值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a matrix and I want to find the indices and values that larger than a threshold,so how to do it with CUDA? Or it's a better way to copy the matrix to memory and let cpu do the work?

推荐答案

您可以使用以下方法轻松实现推力,它为您提供了所需的基本构件。以下代码首先找到满足条件的索引(值>阈值),然后提取相应的值。如果不需要索引,则可以一步一步完成所有操作。

You can implement this very easily using Thrust, which offers you the basic building blocks you need. The following code first finds the indices which fulfill the condition (value > threshold) and then extracts the corresponding values. If you don't need the indices, you can do all this in one step.

#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 

这篇关于查找大于CUDA中阈值的索引和值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆