arraysindexingmatlab-coder

Error in Matlab Coder: Index exceeds array dimensions


I am trying to convert .m script to C++ using MATLAB Coder.

function P=r_p(1,var1,var3)
p=[[3,7]              
[10,15]
[6,19]
[21,19]
[43,11]
[969,2]
[113,9]
[43,59]
[21,15]
[6,15]
[10,18]
[3,15]];
tmax=sum(p(:,1))+41;
coder.varsize('x');         
x=ones(9,11).*[0:10:100];   % getting error in this line: [9x11]~=[1x11]. Since size of x is varying in for loop, so i should tell coder that it is variable size, So I used Varsize
for t=11:tmax
  a1=(rand-0.5)*1;
  a9=(rand-0.5)*1.25;
  a2=(rand-0.5)*1.5;
  a8=(rand-0.5)*1.75;
  a3=(rand-0.5)*2.0;
  a7=(rand-0.5)*2.25;
  a4=(rand-0.5)*2.5;
  a6=(rand-0.5)*2.75;
  a5=(rand-0.5)*3;
  x(1,t+1)=x(1,t)+a1;
    if x(1,t+1)<(100-var1) || x(1,t+1)>(100+var1)       % loop 1: x(1,11)+a1 value is is writing to x(1,12) So coder gives error "Index exceeds array dimensions. Index value 12 exceeds valid range [1-11] of array x".
      x(1,t+1)=x(1,t);                                  % In matlab it works fine, but coder throws error. 
    end                                                
 end

My question is Let say loop 1, x(1,12)= x(1,11)+a1 In matlab this assignment works fine, but when converting it is throwing error " Index exceeds array dimensions. Index value 12 exceeds valid range [1-11] of array x" As I declared x as variable size coder should assign x(1,11)+a1 value to x(1,12) but it is not doing, instead throwing error. Why?

Since t is looping for 1289, if I specify bounds for x like coder.varsize('x',[1290,1290],[0,0]) then Coder gives error in other part of the code i.e dimensions doesn't match. Ofcourse it should because dimension of x doesn't match with [ones(12,9)p(1,2)/9;(P_1s+var3/100P_1s.*randn(size(P_1s))/2)/9;zeros(30,9)].

  1. is declaring x as variable size is correct step or not? if yes then what should be the work around for "index exceeds array dimensions error"

Please Let me know, what am I missing to convert it to C++ code


Solution

  • MATLAB Coder doesn't support 2 things you're using here: implicit expansion and growing arrays by assigning past the end of a dimension.

    For implicit expansion, you can use:

    x=bsxfun(@times,ones(9,11),[0:10:100]);
    

    Assigning past the end of an array in MATLAB will grow the array. That's an error in Coder. There are 2 ways to overcome this:

    In this example, you know tmax so I'd suggest just changing the allocation of x to have the right number of columns up front:

    % Current initial value
    x=bsxfun(@times,ones(9,11),[0:10:100]);
    % Extra columns - please check my upper bound value
    x=[x, zeros(9,tmax)];