Can this algorithm be simplified (written cleaner)?
I have this algorithm, but I am not too keen on the many if-statements.
Can someone see if this function can be written in a cleaner way?
rand('twister',101)
n = 10;
f = A.^(0:n)./factorial(0:n);
f = f/sum(f);
n = 10000;
Xi = 2;
X = zeros(1,n);
for i =1:n,
dXi = (-1)^round(rand);
Yi = Xi + dXi;
if Yi > 0 & Yi <= length(f),
开发者_C百科 if f(Yi) >= f(Xi),
X(i) = Yi;
Xi = Yi;
else
if rand <= f(Yi)/f(Xi),
X(i) = Yi;
Xi = Yi;
else
X(i) = Xi;
end
end
end
X(i) = Xi;
end
I don't know Matlab syntax, but generally something like this:
if (cond1) then
mainAction
else if (cond2) then
mainAction
else
otherAction
can be simplified as:
if (cond1 OR cond2) then
mainAction
else
otherAction
The OR
would have to be short-circuiting for exact equivalence, but if cond2
has no side-effects then it doesn't really matter.
This can be simplified by noting that whenever you do X(i) = Yi
you also do Xi = Yi
and therefore you could just assign X(i) once at the end of the loop. This allows a lot of the other logic to simplify.
Also note that the ,
at the end of an if-clause is really only necessary in one-line if statements, e.g.
if x < y, do_something, else do_something_else, end
Anyway I get this (you could simplify further into one if statement but perhaps that's less clear. Also having more than one if statement allows breakpoints on particular sections.):
for i =1:n,
dXi = (-1)^round(rand);
Yi = Xi + dXi;
if Yi > 0 & Yi <= length(f)
if f(Yi) >= f(Xi) || rand <= f(Yi)/f(Xi)
Xi = Yi;
end
end
X(i) = Xi;
end
精彩评论