Coder varsize "index exceeds dimensions"

3 次查看(过去 30 天)
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
end
end
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 -report
Code generation successful: View report
Pulling up code report, shows that z is assgined as a variable size output as a ":10000x1 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] of
array 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

采纳的回答

Ryan Livingston
Ryan Livingston 2014-4-17
There are some MATLAB idioms which are not supported for code generation. Many such limitations are in the interest of preserving code quality.
In this case, the two nested loops are increasing the size of z by indexing and assigning the value one past the end of z in each iteration where the if condition is true. This practice is not supported for code generation:
The technique you employed, z = [z;x(i)*y(j)], is a commonly used solution in cases like these.

更多回答(1 个)

Anup
Anup 2014-4-17
Thanks Ryan.

产品

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by