New to Thrust - element wise (Hadamard Product)

Good Afternoon,

I am new to using CUDA Thrust and was wondering if anyone could give some guidance. I would like to create an element wise multiplication for two vectors (e.g., a Hadamard Product) using Thrust with complex floating-point numbers. I would guess it would be a call to thrust::transform but I don’t think any of the standard operations passed to it would apply given it is a product of complex numbers. However, I could be wrong as I am new to Thrust.

Any help would be appreciated.


thrust natively supports complex calculation. You can define a thrust vector with a complex type just as you would with other supported types.

$ cat
#include <thrust/device_vector.h>
#include <thrust/host_vector.h>
#include <thrust/complex.h>
#include <thrust/transform.h>
#include <thrust/copy.h>
#include <thrust/functional.h>
#include <iostream>

const int len = 2;
using mt = thrust::complex<float>;
int main(){

  thrust::device_vector<mt> a(len, {1,2});
  thrust::device_vector<mt> b(len, {2,3});
  thrust::device_vector<mt> c(len);
  thrust::transform(a.begin(), a.end(), b.begin(), c.begin(), thrust::multiplies<mt>());
  thrust::host_vector<mt> h_c=c;
  thrust::copy_n(h_c.begin(), len, std::ostream_iterator<mt>(std::cout, ","));
  std::cout << std::endl;
$ nvcc -o t2087
$ compute-sanitizer ./t2087
========= ERROR SUMMARY: 0 errors

This may also be of interest.

Thanks @Robert_Crovella

Stupid me, I had neglected to add the c.begin() in the thrust::transform function and was just passing it the b.end(), as in following:

thrust::transform(a.begin(), a.end(), b.begin(), b.end(), thrust::multiplies<mt>())

It was a Monday :)

Thank you for the reply. I have now corrected it and all works as expected.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.