MATLAB: Index in position 2 exceeds array bounds(must not exceed 1). How to fix it? The error addresses at the last equation R(1,m).

indexMATLAB

R1(1,1)=35; % Initial pop of males
R1(2,1)=35; % Initial pop of females
P1(3,1)=200000; % Initial pop of plants
R1(4,1)=2; % Initial pop of male snakes
R1(5,1)=2; % Initial pop of female snakes
r(1)=1.01; % Growth rate of male pop
r(2)=1.01; % Growth rate of female pop
r(3)=1.10; % Growth rate of plants pop
r(4)=1.05; % Growth rate of male snakes
r(5)=1.05; % Growth rate of female snakes
K(1)=800; % Carrying capacity for male pop
K(2)=600; % Carrying capacity for female pop
K(3)=7500000; % Carrying capacity for plants pop
K(4)=100; % Carrying capacity for male snakes
K(5)=120; % Carrying capacity for female snakes
Er=65; % Plants per animal
Ap=150000; % Animal 'Plant needs'
Ri=R1(1,1)+R1(2,1); % Sum of two genders
rp=r(3)*P1(3,1); % Mathusian growth
% Plants population
NM = 520; % Months of simulation
for i = 2:NM
P(1,i)=rp*P1(3,1)*((K(3)-P1(3,1))/K(3))*(Er*Ri);
end
% Lemur population male and female
NM = 200; % Months of simulation
for m = 2:NM
R(1,m)=r(1)*R1(1,m-1)*((K(1)-R1(1,m-1))/K(1))*(Er/Ap);
R(2,m)=r(2)*R1(2,m-1)*((K(2)-R1(2,m-1))/K(2))*(Er/Ap);

Best Answer

Your ‘R1’ array when called initially in this line:
R(1,m)=r(1)*R1(1,m-1)*((K(1)-R1(1,m-1))/K(1))*(Er/Ap);
is a (5x1) vector. When ‘m’ is greater than 2, your ‘R1(1,m-1)’ reference is to a column that does not exist.
One way of avoiding that is to preallocate ‘R1’ (and perhaps others, I did not examine your code in detail) to be whatever size you eventually want it to be.
Related Question