Search code examples
cudamexthrustcusp-library

Accessing real and imaginary parts of cusp::complex vector


I need to access the real and imaginary parts of a cusp::complex type vector, for the purpose of sending it to a matlab variable through, mex. How do I access the real and imaginary parts separately of a vector of type.

    cusp::array1d<cusp::complex<double>,cusp::host_memory> x;

I am at the moment making two std::vectors and looping through it.

    std::vector<double> xreal(n); 
    std::vector<double> ximag(n);        
    for(int i=0;i<n;i++){
        xreal[n]=x[i].real();
        ximag[n]=x[i].imag();
    }

And then transfering it to a matlab variable using thrust.

    mxArray *T = mxCreateDoubleMatrix(n, 1, mxCOMPLEX);
    double *tp_real  = mxGetPr(T);
    double *tp_imag  = mxGetPi(T)
    thrust::copy(xreal.begin(), xreal.end(), tp_real);
    thrust::copy(ximag.begin(), ximag.end(), tp_imag);
    plhs[0] = T;

I want to know how I can use thrust for accessing the real and imaginary parts of the complex array

    cusp::array1d<cusp::complex<double>,cusp::host_memory> x; 

to transfer it through the corresponding real and imaginary pointers of the mxArray. directly, so that I can avoid the loop.


Solution

  • Ok so I have managed to solve it using functors, I made two functors (not sure if this is called a functor, but anyways)

        __host__ double realpart(cusp::complex<double> val){
            return val.real();
        }
    
        __host__  double imagpart(cusp::complex<double> val){
            return val.imag();
        }
    

    And used thrust::transform

        cusp::array1d<double,cusp::host_memory>xreal(n);
        cusp::array1d<double,cusp::host_memory>ximag(n);
        thrust::transform(x.begin(),x.end(),xreal.begin(),realpart);
        thrust::transform(x.begin(),x.end(),ximag.begin(),imagpart);
    

    It worked, and then I could fill it normally using thrust::copy to the pointer. It doesnt work for a device_memory array. I tried adding __device___ to the functor, but it did not work.