MATLAB: How to populate an mxArray with NaN values

MATLABmxarraynan

I would like to create an mxArray that can store a NaN (not-a-number) value. An example which shows how to do this will be useful.

Best Answer

You will need to use mxCreateScalarDouble and mxGetNaN to create a NaN value. NaN is the IEEE arithmetic representation for Not-a-Number. The value of Not-a-Number is built in to the system. You cannot modify it. Therefore you can use the macro mxGetNaN to define your system's Not-a-Number.
Here is example code on how to implement this in your C-Mex function.
#include "mex.h"
void mexFunction(int nlhs, mxArray * plhs[],
int nrhs, const mxArray * prhs[])
{
mxArray * intvalue,
* nanvalue;
int dim[1]={2};
intvalue=mxCreateDoubleScalar(5);
nanvalue=mxCreateDoubleScalar(mxGetNaN());
plhs[0]=mxCreateCellArray(1,dim);
mxSetCell(plhs[0],0,intvalue);
mxSetCell(plhs[0],1,nanvalue);
}