MATLAB: Do I receive an error “Can’t index into an empty array” when calling the C++ MEX function in MATLAB

allocateallocationcppMATLABmatlab::data::arrayfactorymatlab::data::typedarraymatlab::mex::argumentlistmemoryreturn

I have created a short C++ MEX program which outputs a single scalar value. The operator() function for this program is included below:
void operator()(matlab::mex::ArgumentList outputs, matlab::mex::ArgumentList inputs) {
outputs[0][0] = 5;
}
The MEX program compiles without warnings, but I get the following error when I call the MEX function in MATLAB:\n
Can't index into an empty array
How do I resolve this issue?

Best Answer

This error is occurring because the memory for the output is not being allocated before assigning the output value. 
In order to allocate the memory for the output, you can use an object of type "matlab::data::ArrayFactory". This "matlab::data::ArrayFactory" object can allocate memory for a "matlab::data::TypedArray" object, which can then be populated with the data that will be returned to MATLAB. After these two steps, this populated "matlab::data::TypedArray" object can be assigned to the output in the "matlab::mex::ArgumentList" object.
For example, the following code creates an "matlab::data::ArrayFactory" object, uses the object to allocate a "matlab::data::TypedArray" object containing the value 5, and then assigns the "matlab::data::TypedArray" to be the first output.
void operator()(matlab::mex::ArgumentList outputs, matlab::mex::ArgumentList inputs) {
matlab::data::ArrayFactory factoryObject;
matlab::data::TypedArray<double> allocatedDataArray = factoryObject.createScalar<double>(5);
outputs[0] = allocatedDataArray;
}
When this code is used in a C++ MEX program, the value of 5 will be returned to MATLAB. 
For more information about using input and output arguments in a C++ MEX function, see the "Passing Arguments" section of the following documentation page: