Hello, I am new to Matlab codegen, and was trying out a simple test with the following function:
function z = fun_try_mex(x,y)del = 1;k=1;z=ones(1,1);for i=1:size(x,2) for j=1:size(y,2) coder.varsize('z',[10000 1],[1 0]); if (x(i)<del && y(j)<del) z(k) = x(i)*y(j); k=k+1; end endend
When i do mex code generation, I have no issues –
>>cfg = coder.config('mex');>> cfg.DynamicMemoryAllocation = 'AllVariableSizeArrays';>> codegen -config cfg -args {x, y} fun_try_mex.m -reportCode generation successful: View report
Pulling up code report, shows that z is assgined as a variable size output as a ":10000×1 double".
If I try to run the mex function, however, I get the following error:
x=-10:1e-1:10;y=-20:1e-1:20;*>>z1=fun_try_mex_mex(x,y)*Index exceeds matrix dimensions. Index value 2 exceeds valid range [1-1] ofarray z.Error in fun_try_mex (line 13)** z(k) = x(i)*y(j);
Can anyone help me understand why this could be? The non-mex version of the function works with no errors.
Thanks in advance,
anup
—– EDIT 2 Ok, so I tried something else. Instead of referencing the array index and assigning it the calculated value, I tried only appending to the last value of the vector i.e.
Original:
z(k) = x(i)*y(j);
Change to:
z = [z;x(i)*y(j)];
And now regenerating the code, the functions works! but now i always get an additional row or column entry in the output array. It seems strange to me that the auto coder cannot understand the referencing of the array in the function.
thanks
anup
Best Answer