MATLAB: Mex file giving wrong outputs

MATLAB

Hi, I am generating a mex file for my State Space equation and running it on GPU. When I am running the mex file, I am getting different outputs than expected.
My State Space Equation is:
function out = stateequation(a,b,c,d,x,u) %#codegen
n = size(u,2);
coder.gpu.kernel()
for i = 1:n
x(:,i+1) = a*x(:,i)+ b*u(:,i); %% State Equation
end
out = c*x(:,1:n)+ d*u(:,1:n); %% Output equation
end
On running this code, I am getting answer as :
24 156 948
24 156 948
24 156 948
I have generated mex file using codegen method as follows:
A = double(zeros(3,3));
B = double(zeros(3,3));
C = double(zeros(3,3));
D = double(zeros(3,3));
X = double(zeros(3,1));
U = double(zeros(3,3));
cfg = coder.gpuConfig('mex');
codegen -args {A,B,C,D,X,U} -config cfg stateequation
But on running this mex file I am getting result as :
156 156 156
156 156 156
156 156 156
Why it is giving different answer? Can Someone help me with this?
Thank you in advance

Best Answer

  • 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:
    %% content of stateequation_tb.m
    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];
    % call function
    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) %#codegen
    n = size(u,2);
    coder.gpu.kernel()
    z = zeros(size(x,1),n+1); %% Define a local variable of the right size
    z(:,1:size(x,2)) = x; %% Copy x into the corresponding locations of z
    for i = 1:n
    z(:,i+1) = a*z(:,i)+ b*u(:,i); %% State Equation
    end
    out = c*z(:,1:n)+ d*u(:,1:n); %% Output equation
    end
    If you regenerate the MEX file now, you should get correct results.