Matlab Coder 中的错误:索引超出数组维度

Error in Matlab Coder: Index exceeds array dimensions

我正在尝试使用 MATLAB Coder 将 .m 脚本转换为 C++。

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

我的问题是假设循环 1, x(1,12)= x(1,11)+a1 在 matlab 中,此赋值工作正常,但在转换时抛出错误“索引超出数组维度。索引值 12 超出数组 x 的有效范围 [1-11]”正如我将 x 声明为可变大小编码器应该将 x(1,11)+a1 值分配给 x(1,12) 但它没有这样做,而是抛出错误。为什么?

由于 t 循环 1289,如果我为 x 指定边界,例如 coder.varsize('x',[1290,1290],[0,0]) 然后编码器在代码的其他部分给出错误,即尺寸不匹配。当然应该是因为 x 的维度与 [ones(12,9)p(1,2)/9;(P_1s+var3/100 不匹配P_1s.*randn(size(P_1s))/2)/9;zeros(30,9)].

  1. 将 x 声明为可变大小是否正确?如果是,那么“索引超出数组维度错误”应该如何解决

请告诉我,我缺少什么将它转换为 C++ 代码

MATLAB Coder 不支持您在此处使用的 2 个东西:implicit expansion and growing arrays by assigning 超过维度的末尾。

对于隐式扩展,您可以使用:

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

在 MATLAB 中赋值超过数组末尾将使数组增长。这是编码器中的错误。有两种方法可以克服这个问题:

  • 分配您的数组以预先拥有正确数量的元素
  • 使用串联增长数组:x = [x, newColumn]

在这个例子中,你知道 tmax 所以我建议只更改 x 的分配以在前面获得正确的列数:

% 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)];