Main Content

mxMakeArrayComplex (C)

Convert real mxArray to complex, preserving real data

C Syntax

#include "matrix.h"
int mxMakeArrayComplex(mxArray *pa);

Description

Use mxMakeArrayComplex to convert a real mxArray to a complex mxArray. The real part of the updated array contains the real data from the original array.

If pa is empty, then the function returns a complex empty mxArray.

If pa is complex, then the function does nothing.

Input Arguments

expand all

Pointer to a numeric mxArray array.

Output Arguments

expand all

Function status, returned as int. If successful, then the function returns 1.

Returns 0 if unsuccessful. The function is unsuccessful if pa is NULL, nonnumeric, or read-only.

Examples

Suppose that your application processes complex data and you create complex mxArrays to handle the data. If you pass a complex array containing only real data to a MATLAB® function, then the returned value is a real array. For example, call the MATLAB sqrt function with the following input.

a = complex([2,4])
a =

   2.0000 + 0.0000i   4.0000 + 0.0000i

Although the input argument is complex, the data is real-only, and the output of the function is no longer complex.

a1 = sqrt(a)
a1 =

    1.4142    2.0000

To maintain the complexity of the data, use the mxMakeArrayComplex function to wrap the result. To build the MEX file complexFnc.c:

mex -R2018a complexFnc.c
void mexFunction( int nlhs, mxArray *plhs[],
                  int nrhs, const mxArray *prhs[] )
{
    mxArray *rhs[1], *lhs[1];
    
    /* check for the proper number of arguments */
    if(nrhs != 1) {
        mexErrMsgIdAndTxt("MATLAB:complexFnc:checkrhs","1 input required.");
    }

    if(nlhs > 1) {
        mexErrMsgIdAndTxt("MATLAB:complexFnc:checklhs","Too many output arguments.");
    }

#if MX_HAS_INTERLEAVED_COMPLEX
        
    /* get the square root */
    rhs[0] = mxDuplicateArray(prhs[0]);
    mexCallMATLAB(1, lhs, 1, rhs, "sqrt");
    if(!mxIsComplex(lhs[0])) {
        /* preserve complexity of data */
        mxMakeArrayComplex(lhs[0]);
    }

    plhs[0] = mxDuplicateArray(lhs[0]);
#endif
}

Version History

Introduced in R2018a