MATLAB: Help me make this small inner loop faster – more efficient notation or functions

MATLABoptimizationspeed

I have some code which runs this inner loop a LOT of times for different values of Ri and Ii:
z = complex(Ri,Ii);
for (k=1:50)
e1 = eval(formula);
e2 = eval(derivative);
z = z - e1/e2 / (1 - (e1*eval(derivative2))/(2*power(e2,2.0)));
g = power(real(z),2)+power(imag(z),2);
if (k>1 && abs(g-gprev)<epsilon)
break;
end
gprev = g;
end
Formula is a string expression involving "z" (input by user at run-time, so can't be hardcoded) and derivative is it's symbolic derivative. I know eval() is supposed to be subs() but that seems to make it way slower. Is there anything I should be doing in terms of choosing better functions or notation that would help speed this up?

Best Answer

  • Using eval is not only not necessary, it will cause problems.
    I would do something like this instead:
    z = complex(rand,rand);
    Deriv = @(f,x) (f(x+1E-8)-f(x))/1E-8;
    Formula_str = 'exp(-x)*cos(x)';
    Formula = str2func(['@(x) ' vectorize(Formula_str)]);
    Derivative = Deriv(Formula,z);
    e1 = Formula(z);
    e2 = Derivative;
    Use the str2func function to create an executable anonymous functon from the input string. The ‘Deriv’ function is a reliable way of calculating derivatives of anonymous functions.
    This has the advantage of running correctly, and avoids the Symbolic Math Toolbox that is likely not necessary here. It is also likely faster, although I didn’t time it.