mxMakeArrayReal (C) - Convert complex mxArray to real, preserving real

        data - MATLAB ([original](https://www.mathworks.com/help/matlab/apiref/mxmakearrayreal.html)) ([raw](?raw))

Convert complex mxArray to real, preserving real data

C Syntax

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

Description

Use mxMakeArrayReal to convert a complexmxArray to a real mxArray. The array contains the data from the real part of the original array. If the originalmxArray is real, 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 determines that real numbers are the only meaningful result. If complex results occur because of noise in the data, then the program drops small imaginary parts. However, if the imaginary part exceeds a threshold, then the program throws an error.

In the following example dropComplexIfUnderThreshold.c, the threshold limit is set to .2.

#include "mex.h"

/* dropComplexIfUnderThreshold converts input to a real double scalar

{ #define LIMIT .2

/* check for the proper number of arguments */
if(nrhs != 1) {
    mexErrMsgIdAndTxt("MATLAB:dropComplexIfUnderThreshold:checkrhs","1 input required.");
}

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

if( !(mxIsDouble(prhs[0]) && mxIsScalar(prhs[0])) ) {
    mexErrMsgIdAndTxt("MATLAB:dropComplexIfUnderThreshold:checkdouble","rhs[0] must be double scalar.");
}

plhs[0] = mxDuplicateArray(prhs[0]);

if(mxIsComplex(prhs[0])) {

#if MX_HAS_INTERLEAVED_COMPLEX mxComplexDouble *dt = mxGetComplexDoubles(prhs[0]);

    /* test imaginary data for significance */
    if( dt[0].imag < LIMIT) {
        mxMakeArrayReal(plhs[0]);
    }
    else {
        mexErrMsgIdAndTxt("MATLAB:dropComplexIfUnderThreshold:outOfBounds","Data error.");
    }

#else mxDouble *dt = mxGetPi(plhs[0]);

    /* test imaginary data for significance */
    if (dt[0] < LIMIT) {
        mxFree(mxGetPi(plhs[0]));
        mxSetPi(plhs[0], 0);
    } else {
        mexErrMsgIdAndTxt("MATLAB:dropComplexIfUnderThreshold:outOfBounds","Data error.");
    }

#endif } }

To build the MEX file, type:

mex -R2018a dropComplexIfUnderThreshold.c

To test the function, type:

dropComplexIfUnderThreshold(3)

dropComplexIfUnderThreshold(complex(3,.1))

dropComplexIfUnderThreshold(complex(1,.2))

Error using dropComplexIfUnderThreshold Data error.

Version History

Introduced in R2018a