If you work with MATLAB Coder or GPU Coder and experience runtime issues (e.g. wrong results or crashes), it is always a good idea to use the MATLAB/GPU Coder App. The Apps have a useful feature that helps detect runtime issues.
To do this, you first need to write a testbench script (say stateequation_tb.m) that calls stateequation.m and produces the output that you show above:
a = [2 2 2;2 2 2;2 2 2];
b = [2 2 2;2 2 2;2 2 2];
c = [2 2 2;2 2 2;2 2 2];
d = [2 2 2;2 2 2;2 2 2];
x = [2;2;2];
u = [2 2 2;2 2 2;2 2 2];
out = stateequation(a,b,c,d,x,u)
Open GPU Coder App, specify the function stateequation.m and its associated testbench stateequation_tb.m, and select "Check for issues on CPU". The following runtime error should be thrown:
Index exceeds array dimensions. Index value 2 exceeds valid range [1-1] for array 'x'.
This happens because the size of the input array X is modified during runtime. While MATLAB is able to handle this (which is why MATLAB is so cool and easy to use! :-) ) this does not go well if your aim is to go into C/CUDA code generation.
This can be fixed by using a correctly sized array that copies 'x' like:
function out = stateequation(a,b,c,d,x,u)
n = size(u,2);
z = zeros(size(x,1),n+1);
z(:,1:size(x,2)) = x;
for i = 1:n
z(:,i+1) = a*z(:,i)+ b*u(:,i);
out = c*z(:,1:n)+ d*u(:,1:n);
If you regenerate the MEX file now, you should get correct results.