0
votes

I am using MATLAB coder to generate code which deals with complex numbers. The default typedef for the complex type generated by MATLAB is:

typedef double real_T;//real number
typedef struct {
  real_T re;
  real_T im;
} creal_T;//complex number

Now, I want to use fftw3 to perform fft on the data, the problem is that in fftw3 the complex type is defined as:

typedef double fftw_complex[2];

From the fftw3 documentaion in the "Upgrading from fftw Version 2" section:

The main difference in data types is that fftw_complex in FFTW 2 was defined as a struct with macros c_re and c_im for accessing the real/imaginary parts. (This is binary compatible with FFTW 3 on any machine except perhaps for some older Crays in single precision.) The equivalent macros for FFTW 3 are:

 #define c_re(c) ((c)[0])
 #define c_im(c) ((c)[1])

Am I missing something here or is there a way to cast, safely, the creal_T type to the corresponding fftw3 without actually copying the data element by element?

2

2 Answers

2
votes

The complex number format used by MATLAB Coder and what you show from FFTW are the same format, usually referred to as interleaved complex. They are binary compatible. So you should be able to do a pointer or reinterpret cast to convert between them without copying data.

It is true that MATLAB historically used separate (aka split) complex before R2018a. However, you are not interacting with the MATLAB complex type here. You are using the MATLAB Coder generated complex type.

Starting in R2017b MATLAB Coder can generate code from the MATLAB FFT functions that calls FFTW for you:

https://www.mathworks.com/help/coder/ug/speed-up-fast-fourier-transforms-in-generated-standalone-code-by-using-fftw-library-calls.html

That would allow you to write fft(x) in MATLAB and have all of the FFTW code produced automatically for you by MATLAB Coder.

2
votes

EDIT: If you are dealing with MATLAB MEX-files, read this answer. If you are dealing with MATLAB Coder, as the OP seems to be, read Ryan Livingston’s answer instead.

—-

The only correct way to use FFTW with MATLAB's complex representation is to use the "Guru interface", which supports "split arrays" as they call it. This is the format that MATLAB uses (real and imaginary components are separate arrays). Here is a link to the documentation page.

Note that, starting with MATLAB R2018a, MATLAB stores complex numbers in the "normal" way, interleaving real and imaginary values. So the alternative is to upgrade MATLAB. See "MATLAB Support for Interleaved Complex API in C MEX Functions".