I am running a loop of deterministic simulation using perfect_foresight_solver.m. The total running time is about 6 hours, and the profiler tells me that a single funcion getPowerDeriv.m uses about half of the total time. This function calculates the k-order derivative of x^p. It uses a series of “if” conditions and a “for loop”. I wonder if we can improve it. I attach the function below.
function dxp=getPowerDeriv(x,p,k)
if (abs(x) < 1e-12) && (p > 0) && (k > p) && (abs(p - round(p)) < 1e-12)
dxp = 0;
else
dxp = x^(p-k);
for i=0:k-1
dxp = dxp*p;
p = p-1;
end
end
end