Reputation: 3080
I am implement the function to get the value of W with input is k, epsilon, and Omega. The function W is defined as
Please don't worry about the complex of equation. It is very easy with three known parameter k, epsilon and Omega. Now, I want to implement it in matlab. However, my problem is how to set the range of first loop with upper range min(g-1,k). Let see my implementation for more detail. Is it correct
function W=getW(k,epsilon,Omega)
n=ceil((1+epsilon)*k);
sumIn=0;
sumOut=0;
g=2;
for h=1 :min(n-1,k)
for g=2:n
sumIn=sumIn+(g-h)*getA(k,epsilon,g,Omega)*getT(k,g,h);
end
sumOut=sumOut+sumIn;
end
sumOut
end
function A=getA(k,epsilon,g,Omega)
n=ceil((1+epsilon)*k);
A=nchoosek(n,g)*(Omega)^g*(1-Omega)^(n-g)
end
function T=getT(k,g,h)
T=nchoosek(k,h)*getS(g,h)/(k^g);
end
function S=getS(g,h)
sumSX=0;
for x=1:h-1
sumSX=sumSX+(-1)^(x-h+1)*nchoosek(h,x)*x^g;
end
S=h^g-sumSX;
end
To run it set W=getW(500,0.1,0.02)
Upvotes: 0
Views: 241
Reputation: 387
It does not work because Matlab don’t check the line with FOR again, at least it does not in the debugger. I guess when Matlab interprets the line for h=1 :min(g-1,k)
it calculates ones how many times it needs to repeat the loop. In this case it is once because g is 2. Even when g changes it never checks that line again. To avoid this just use while for the outer loop. With
function W=getW(k,epsilon,Omega)
n=ceil((1+epsilon)*k);
sumOut=0;
g=2;
h=1;
while(h <= min(g-1,k))
sumIn=0;
for g=2:n
sumIn=sumIn+(g-h)*getA(k,epsilon,g,Omega)*getT(k,g,h);
end
sumOut=sumOut+sumIn;
h=h+1;
end
function A=getA(k,epsilon,g,Omega)
n=ceil((1+epsilon)*k);
A=nchoosek(n,g)*(Omega)^g*(1-Omega)^(n-g)
end
function T=getT(k,g,h)
T=nchoosek(k,h)*getS(g,h)/(k^g);
end
function S=getS(g,h)
sumSX=0;
for x=1:h-1
sumSX=sumSX+(-1)^(x-h+1)*nchoosek(h,x)*x^g;
end
S=h^g-sumSX;
end
Upvotes: 1
Reputation: 26318
I think the condition you're looking for is:
min((1+epsilon)*k - 1, k);
The g-1
is supposed to be evaluated after the right hand side loop is done, and take the last value of g
.
Upvotes: 1