MATLAB: How to convert interpn() to C

matlab coder

To get to know Matlab coder I would like to convert the following code to C:
function [] = Test()
x = [1 2 3 4 5 6 7];
% values of sample points
v = [7 16 31 10 6 0 1];
%query points in x
xq = (1:0.1:7);
%call interpn()
vq = interpn(x,v,xq, 'cubic');
if coder.target('MATLAB')
if ~isempty(vq)
figure
plot(x,v,'o',xq,vq,'-b'); hold on;
legend('Samples', 'Cubic Interpolation');
end
end
The C code it produces is as follows:
:
:
/* Function Definitions */
void Test(void)
{
/* values of sample points */
/* query points in x */
/* call interpn() */
}
/* End of code generation (Test.c) */
In the C code there is no call to any interpn() function even though the help states that C/C++ code can be generated out of it.
What am I doing wrong?

Best Answer

I don't use MATLAB Coder very often, but I believe I know what's going on.
What in your function uses the output of interpn? The only place vq is used is inside the if coder.target('MATLAB') block and from my reading of the documentation page the body of that if statement will only be entered if the code is "Running in MATLAB (not generating code)". So when generating C code, I suspect that interpn call is being optimized away.
At first I tried defining the function to return vq as an output argument. That caused MATLAB Coder to generate a little more code, but it turns out that the code it generated was just the constant values from that interpn call! MATLAB Coder could tell that the values returned by interpn could be generated at compile-time as constants, and so it simply hard-coded in those values.
When I specified vq as the output and xq as the input (commenting out the line of code that defined xq inside the Test function) and generated code, then I saw some interpolation code being generated.
function vq = Test(xq)
x = [1 2 3 4 5 6 7];
% values of sample points
v = [7 16 31 10 6 0 1];
%query points in x
% xq = (1:0.1:7);
%call interpn()
vq = interpn(x,v,xq, 'cubic');
if coder.target('MATLAB')
if ~isempty(vq)
figure
plot(x,v,'o',xq,vq,'-b'); hold on;
legend('Samples', 'Cubic Interpolation');
end
end