Index out of bounds error

1 view (last 30 days)
Musa
Musa on 11 Feb 2013
I'm trying to simulate random protein production and degradation. I want it so that only one of those 3 outcomes can occur in any one loop. I keep getting this error though:
_Attempted to access N(1248); index out of bounds because numel(N)=1247.
Error in Assignment_2 (line 11)
p2 = DegradationRate*DeltaTime*N(n-1);_
Every time I run the program, the error is at different values. Here is my code so far:
clear
N0=0;
DegradationRate = 0.01;
ProductionRate = 1;
DeltaTime = 0.1;
MaxTime=500;
N(1)=N0;
for n = 2:(MaxTime/DeltaTime+1)
p1 = ProductionRate*DeltaTime;
p2 = DegradationRate*DeltaTime*N(n-1);
pRandom = rand(1);
if pRandom < p1
N(n)=N(n-1)+1;
end
if p1 <= pRandom < p2
N(n)=N(n-1)-1;
end
if (p1+p2) < pRandom
N(n)=N(n-1);
end
end
Time = 0:DeltaTime:(MaxTime/DeltaTime);
plot(Time,N,'r')
I tried my best to play around with it, but I can't seem to get rid of that error. Any help will be appreciated!

Accepted Answer

Walter Roberson
Walter Roberson on 11 Feb 2013
If none of the three "if" conditions hold then you do not assign to N(n). You also have not preallocated N, which you should do for efficiency.
Part of your problem is that p1 <= pRandom < p2 does not do what you think it does. It means ((p1 <= pRandom) < p2) where the (p1 <= pRandom) returns a logical vector (0 and 1). Change your code to
if (p1 <= pRandom) & (pRandom < p2)

More Answers (0)

Categories

Find more on Get Started with MATLAB in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!