How to execute a while loop?

1 view (last 30 days)
Christianne
Christianne on 3 Oct 2014
Answered: Geoff Hayes on 3 Oct 2014
I created a function to find the optimal S(i) for certain data. In the first paragraph i calculate the GAW total when the S(i) = 0 for all i. Then the system is checking if the GAWtotal is more than the GAW target. As this is the case it will calculate the GAGAMMA for every i. For the highest GAGAMMA yields that we add one to S(i). Then we will calculate the GAWtotal again and check of the GAWtotal is more than the GAWtarget. As long as the GAWtotal is higher than the GAWtarget we will execute this loop. When the GAWtotal is lower than the GAWtarget the loop will stop end we want to know the S(i). Still in doesn't works? Where did i go wrong?
function [Sfinal] = calcSfinal(mday,t,C,M, GAWtarget)
% This function calculates the EBO based on the input
for i=1:size(mday,1);
S(i)=0;
for k=0:S(i)
EBO1(k+1)=(S(i)-k)*poisspdf(k,mday(i)*t(i));
end
GAEBO(i)=mday(i)*t(i)-S(i)+sum(EBO1)
GAEBOtotal=sum(GAEBO);
end
GAWtotal=GAEBOtotal/M;
while GAWtotal>GAWtarget
for i=1:size(mday,1);
S(i)=0;
for k=0:S(i)
EBO2(k+1)=poisspdf(k,mday(i)*t(i));
end
GAGAMMA(i)=(1/C(i))*(1-sum(EBO2));
[value,index]=max(GAGAMMA);
S(index)=S(index)+1;
for k=0:S(i)
EBO3(k+1)=(S(i)-k)*poisspdf(k,mday(i)*t(i));
end
GAEBO(i)=mday(i)*t(i)-S(i)+sum(EBO3);
end
GAEBOtotal=sum(GAEBO);
GAWtotal=GAEBOtotal/M;
end
Sfinal(i)=S(i);

Answers (1)

Geoff Hayes
Geoff Hayes on 3 Oct 2014
Christianne - when you ask how to execute a while loop, what exactly do you mean? Do you mean that the while loop is not being entered (because the condition GAWtotal>GAWtarget is always false) or do you mean that the function never terminates because the code becomes stuck in the while loop?
A couple of things: the code calculates EBO1 and EBO3 as
EBO1(k+1)=(S(i)-k)*poisspdf(k,mday(i)*t(i));
EBO3(k+1)=(S(i)-k)*poisspdf(k,mday(i)*t(i));
yet the calculation of EBO2 is
EBO2(k+1)=poisspdf(k,mday(i)*t(i));
So there is no (S(i)-k) factor as there is in the other two. Is this intentional?
As well, on each iteration of the outer for loop, we see that the ith element of the S vector is reset as
while GAWtotal>GAWtarget
for i=1:size(mday,1);
S(i)=0;
% etc.
This means that we lose any of the accumulated "history" when we do
S(index)=S(index)+1;
Is this supposed to happen? If I pass in some dummy data (completely invalid) as
calcSfinal(randi(255,25,1),rand(25,1),randi(255,25,1),4, 12)
then the code becomes stuck in an infinite loop.
If I comment out the line
while GAWtotal>GAWtarget
for i=1:size(mday,1);
% S(i)=0;
% etc.
then the while loop does terminate after a certain number of iterations.

Categories

Find more on Loops and Conditional Statements 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!