Question

In C++, to use complex numbers, I have the struct-type "creal" be defined as

  typedef struct {  
  double re;  
  double im; } creal;  

Now let "length" be the number of elements of the struct array "complex_vector" that is initilized as

creal complex_vector[length];

and is later filled with data.

I would like to extract the two arrays "real_vector" and "imag_vector" from "complex_vector". Until now I have used a for-loop:

double real_vector[length];
double imag_vector[length]; 
for (int n = 0; n < length; n++) 
{ 
    real_vector[n] = complex_vector[n].re;
    imag_vector[n] = complex_vector[n].im;
} 

I wonder if there is a way to avoid the for loop and extract the values of the struct array "complex_vector" directly to create the arrays "real_vector" and "imag_vector".

Thank you for your help.

Was it helpful?

Solution

the loop can not be a avoided since the data in your complex_vector is interleaved

re0 im0 re1 im1 re2 im2 ... reN imN

and your target rep is non interleaved

re0 re1 re2 ... reN
im0 im1 im2 ... imN

so the copying has to be done in any way. how ever you may write the code in a more compact form using some for_each magic but in my opinion this only makes the code more difficult to understand.

edit:
then using some more sophisticated Matrix classes (eg in OpenCV cv::Mat_) this copying can be avoided by using same data buffer but modifying the step size. but this of course comes at the cost of slower element access.

OTHER TIPS

In principal there isn't. There are perhaps ways to write a better for-loop or hide it in a library call, but it will still be a for loop. Examples may be boost zip iterator or std::for_each.

However, your for loop is very simple and clean, so I would leave the code as it is.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top