当行更改大小时索引超出范围?

时间:2018-10-25 04:29:46

标签: arrays matlab indexoutofboundsexception taylor-series

n=[2 5 50];
nn=720; %number of angles
angle=linspace(-2*pi,2*pi,nn); %array of angles
S=zeros(1,nn);
for j=1:3
    z=n(j);
    for i=1:nn
        for k=0:z
            ns=2*k+1;
            S(j,i)=S(j,i)+(-1)^k*(angle(j,i))^(ns)/factorial(ns); 
        end
    end
end

如何定义S,以使错误“位置1的索引超出数组范围(必须不超过1)”不再出现。我尝试在j = 2时更改S(2,nn),但不断弹出相同的错误。

1 个答案:

答案 0 :(得分:2)

S=zeros(1,nn);
[...]
for j=1:3
[...]
S(j,i)=[...]

您将S定义为(1,nn)表,并尝试放入例如S(2,2)的东西。 您的角度索引也错误。它是一维表,您尝试查找元素(例如(2,2)

Fixed code: 

n=[2 5 50];
nn=720; %number of angles
angle=linspace(-2*pi,2*pi,nn); %1-dim table of angles- not a 2-dim table
S=zeros(3,nn); %replaced 1 with 3
for j=1:3
    z=n(j);
    for i=1:nn
        for k=0:z
            ns=2*k+1;
            S(j,i)=S(j,i)+(-1)^k*(angle(i))^(ns)/factorial(ns); %deleted j from angle(i, j) 
        end
    end
end