MATLAB: Have to make a function and return an answer of how long before it passes a certain point. does not work. help needed.

for loopwhile loop

i have to make a function that look like this
n(t)=n(t-1)*(1+alpha*(1-n(t-1)/K))
and know when n(t) surpasses a certain point,N.
my code looks like this:
function tN = bacteriaGrowth(n0,alpha,K,N)
for t=1:20
n(t)=n(t-1)*(1+alpha*(1-n(t-1)/K));
n(0)=n0;
n(1)=n0*(1+alpha*(1-n0/K));
end
if n(t)>=N
tN=t
end
i just get an error in line 4, that doesn't explain what is wrong. help would be very appreciated.

Best Answer

Please consider Stephen's advice and explain, what you observe and what you exactly want to calculate. I try it with a bold guess:
You have to start with n0 before you access n(t-1):
function tN = bacteriaGrowth(n0, alpha, K, N)
n = n0 * (1 + alpha * (1 - n0 / K));
t = 0;
while t < 20 && n < N
for t = 2:20 % Start at 2, because n(1) is defined already
n = n * (1 + alpha * (1 - n / K));
t = t + 1;
end
tN = t;
If you want to reply tN only, storing n in a vector is not useful.
Does this help you? If not, please explain the problem by editing the question, not in the sections for answers or comments. Thanks.