Main Content

Handle Complex Fortran Data

To copy complex data values between a Fortran array and a MATLAB® array, call the mxCopyComplex16ToPtr, mxCopyPtrToComplex16, mxCopyComplex8ToPtr, and mxCopyPtrToComplex8 functions. The example convec.F takes two COMPLEX*16 row vectors and convolves them. This example uses the interleaved complex version of the Fortran Matrix API and assumes a basic understanding of MEX files as described in Create Fortran Source MEX File.

These statements copy data defined by input arrays prhs(1) and prhs(2) into Fortran variables x and y defined as complex*16 arrays.

C     Load the data into Fortran arrays(native COMPLEX data).
      status = 
     +   mxCopyPtrToComplex16(mxGetComplexDoubles(prhs(1)),x,nx)
      if (status .ne. 1) then
            call mexErrMsgIdAndTxt (
     +              'MATLAB:convec:CopyingFailed',
     +              'Could not copy from prhs(1) to complex*16.')
      endif

      status =
     +   mxCopyPtrToComplex16(mxGetComplexDoubles(prhs(2)),y,ny)

      if (status .ne. 1) then
            call mexErrMsgIdAndTxt (
     +              'MATLAB:convec:CopyingFailed',
     +              'Could not copy from prhs(2) to complex*16.')
      endif

Call the convec subroutine.

      call convec(x,y,z,nx,ny)

Copy the results into the MATLAB output array plhs(1).

C     Load the output into a MATLAB array.
      status =
     +   mxCopyComplex16ToPtr(z,mxGetComplexDoubles(plhs(1)),nz)
      if (status .ne. 1) then
            call mexErrMsgIdAndTxt (
     +              'MATLAB:convec:CopyingFailed',
     +              'Could not copy from complex*16 to plhs(1).')
      endif

Build and Test

Verify that you have an installed Fortran compiler.

mex -setup fortran

Copy the convec.F file to a writable folder.

copyfile(fullfile(matlabroot,'extern','examples','refbook','convec.F'),'.','f')

Build the file.

mex -R2018a convec.F

Test the MEX file.

x = [3.000 - 1.000i, 4.000 + 2.000i, 7.000 - 3.000i];
y = [8.000 - 6.000i, 12.000 + 16.000i, 40.000 - 42.000i];
z = convec(x,y)
z =
   1.0e+02 *

Columns 1 through 4 

0.1800 - 0.2600i 0.9600 + 0.2800i 1.3200 - 1.4400i 3.7600 - 0.1200i

Column 5 

1.5400 - 4.1400i

Compare the results with the built-in MATLAB function conv.

conv(x,y)

See Also

Related Topics