MATLAB: How to restart the count in a loop to zero and keep the result of the data stored

while loop

Hello, I need some help with the code below.The solutions is probably very simple but I am unable to get it to work. I need to know how to restart the counter, k, back to zero for the loop within the loop and store the X=k values from the initial loop. The program basically should run one trial, store the result, then run the trail again with a different with the same condition as the first. I had attempted but unable to do it. Any advice will help. Thanks
lambda= 5;
n=100;
U= rand (1,n);
i=1;
k=0
F= exp(-lambda);
while (i<=n)
while (U(1,i)>=F);
k=k+1
F=F+exp(-lambda)*lambda^k/;
end;
i=i+1
end

Best Answer

Make the code a function then call it with different inputs:
function [F, i] = myFun(lambda, n, i, k)
lambda= 5;
n=100;
U= rand (1,n);
i=1;
k=0
F= exp(-lambda);
while (i<=n)
while (U(1,i)>=F);
k=k+1
F=F+exp(-lambda)*lambda^k/;
end;
i=i+1
end
Then call it from your main function:
[F(1), i(1)] = myFun(1, 2, 3, 4);
[F(2), i(2)] = myFun(12432, 343, 1, 55);
[F(3), i(3)] = myFun(111, 222, 456, -42);
Remember to add plenty of comments and to do validation of the inputs to warn user of any bad inputs!