MATLAB: Do I get a domain error regarding complex numbers when running mex functions created by MATLAB Coder 2.4 (R2013a)

matlab coder

I mex some self-written function. For that function, the code generation works perfect. However, when running the code I get an error:
Domain error. To compute complex results from real x, use 'sqrt(complex(x))'.
Error in eml_error (line 20)
eml_rterror(eml_const(msgId),varargin{:});
Error in sqrt (line 14)
eml_error('Coder:toolbox:ElFunDomainError','sqrt');
Error in stcc_garch_likelihood_conditioned_on_stcc (line 58)
stdresid(:,1)=data(:,1)./sqrt(ht(:,1));
This can also happen with functions like LOG:
Domain error. To compute complex results from real x, use 'log(complex(x))'.
The confusing thing is: When I run the non-mexed file, I do not get the error. It works perfectly. Same thing when running it as a script. So, function works perfectly, coding to mex works perfectly, but the mex file doesn't work.

Best Answer

There are basically two cases, between one has to distinguish. On the one side, calling functions in/from MATLAB itself. On the otherside mexing functions with the MATLAB Coder.
When creating a mex file with the MATLAB Coder, the MATLAB Coder creates C-Code and them compiles/builds this code. Thus, for generating C-Code, the compiler explicitly needs to know, which datatypes are passed and used inside the function. However, the coder assumes (in this case), that the data used inside the function is real and not complex.
Complexity is a type in (Embedded) MATLAB, not an attribute. It must always be inferred without the benefit of knowing what the data values are. It can only be inferred based on the type of the input data. This is different from MATLAB, of course, where complexity changes at system run-time.
As the variable for code generation is indirectly assumed as double and real, the code does no more work, when the values passed to SQRT contain negative values. In this case, SQRT would create complex values. As mentioned above, this this no problem, as long as this is done in MATLAB itself, as complexity can change during runtime. However, this can no longer happen if code is generated and in the end a mex file from the MATLAB code. Then, the type of variables is/has to be fixed.
To resolve the problem, it either has to be ensured, that the input to SQRT never will get negative or explicitly make the coder aware, that the output can have complex values, e.g. by using:
sqrt(complex(x))