MATLAB: How to generate codes that does NULL pointer test from MATLAB Coder

matlab coder

I am trying to generate code using MATLAB Coder for the following function:
 
function a = test(b)
%#codegen
% Test in C: if(b!=NULL)
if ~isempty(b)
a = b + 2;
end
end
When I now compile that function test with Matlab Coder into a *.c file (I have configure the input argument 'b' to be a size of 3 double vector for example) the result is: 
 
void test(const real_T b[3], real_T a[3])
{
int32_T i6;
for (i6 = 0; i6 < 3; i6++) {
a[i6] = b[i6] + 2.0;
}
}
 
But I want to have something like: 
 
void test(const real_T b[3], real_T a[3])
{
int32_T i6;
if(b!=NULL)
{
for (i6 = 0; i6 < 3; i6++) {
a[i6] = b[i6] + 2.0;
}
}
}
Is there a way to do this?

Best Answer

In this case, the input was declared to be fixed-size then that assumption is assimilated into the generated code. That is why the empty check is not present in the generated code.
 
There is not a completely general way of checking if something is NULL directly in MATLAB code. Moreover, it does not really make sense for something to be NULL in MATLAB because it is assigned a value, at least a value of '[]'.
However, In releases from R2013a, the MATLAB Coder product has introduced some useful new features which would allow us to do the following. For example, if we want to generate code for the function nullEx.
function success = nullEx
%#codegen
coder.cinclude('<stdio.h>');
% Declare file to be a 'FILE *' and call FOPEN
file = coder.opaque('FILE *', 'NULL', 'HeaderFile', '<stdio.h>');
file = coder.ceval('fopen', ['foo.txt' char(0)], ['r', char(0)]);
% Check that the returned value is not NULL
if file == coder.opaque('FILE *', 'NULL', 'HeaderFile', '<stdio.h>')
success = true;
coder.ceval('fclose', file);
else
success = false;
end
 
You can compile that with:
 
>> codegen nullEx -config:lib -launchreport
 
The code generated will contain 'if (file == NULL)', so similar things can be done for double vector.