Search code examples
arraysmatlabindexoutofboundsexceptiontaylor-series

Index out of bounds when rows change size?


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

How can I define S so that the error "Index in position 1 exceeds array bounds (must not exceed 1)" doesn't come out anymore. I tried changing S(2,nn) when j=2 but the same error keeps on popping up.


Solution

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

    You defined S as (1, nn) table, and you try to put in e.g. S(2, 2) something. You also have wrong indices in angle. It is a 1-dim table and you try to seek element e.g (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