我有两个推力装置矢量,比如说 a 和 b。我想找到向量 a 的索引,其中它小于/大于向量 b 的成对分量($a_{ij}>b_{ij}$)。
我找到了以下有关如何使用标量进行操作的链接:
我的主要问题是变换只需要一个向量作为输入,而对于另一种方法,我不知道如何进行成对比较。
示例: a = {1,3,5,6,9} 和 b = {2,1,4,7,8}。我正在寻找 a_ij >b_ij 的索引。
因此,输出应为 {1,2,4},索引为 0,因为 a 在这些位置大于 b 的成对分量。
这至少部分是一个流压缩问题。 Thrust 提供了流压缩算法,例如
copy_if
。
Thrust 确实有一个
transform
variant 接受两个向量作为输入。您也可以使用 transform_iterator
执行类似的操作。
我认为最紧凑的方法是将
copy_if
与 zip 迭代器和计数迭代器一起使用。有一个 copy_if
变体接受模板数组,非常适合我们的目的。
这是一个例子:
# cat t61.cu
#include <thrust/copy.h>
#include <thrust/iterator/transform_iterator.h>
#include <thrust/iterator/zip_iterator.h>
#include <thrust/iterator/counting_iterator.h>
#include <thrust/device_vector.h>
#include <thrust/host_vector.h>
using mt = int;
using it = unsigned;
struct my_functor
{
template <typename T>
__host__ __device__
bool operator()(T t) { return (thrust::get<0>(t) > thrust::get<1>(t));}
};
int main(){
mt a[] = {1,3,5,6,9};
mt b[] = {2,1,4,7,8};
size_t len = sizeof(a)/sizeof(a[0]);
thrust::device_vector<mt> da(a, a+len);
thrust::device_vector<mt> db(b, b+len);
thrust::device_vector<it> dr(len);
auto my_idx = thrust::counting_iterator<it>(0);
auto my_zip = thrust::make_zip_iterator(thrust::make_tuple(da.begin(), db.begin()));
size_t lr = thrust::copy_if(my_idx, my_idx+len, my_zip, dr.begin(), my_functor()) - dr.begin();
thrust::host_vector<it> hr = dr;
thrust::copy_n(hr.begin(), lr, std::ostream_iterator<it>(std::cout, ","));
std::cout << std::endl;
}
# nvcc -o t61 t61.cu
# ./t61
1,2,4,
#