First, one small quibble: you're not computing 2*A
3 times. You're computing it twice and computing 2*A.^5
once. Note that power operators take precedence over multiplication operators. You could break it up as (2*A).*A.^4
, but you might not be saving yourself much work.
Since you are limited to a single expression inside an anonymous function, there are no particularly clean or efficient ways I can think of to precompute 2*A
in this case. Instead, you could just move the multiplicative factors outside the parentheses to reduce the amount of multiplications you perform. You can rewrite your equation as follows:
fhandle = @(A) 4.*max(0.5 - A,0).*(A.^5 + A + 0.5);
Note that your operation using MAX will be unaffected by moving the factor of 2 outside the operation, since it is simply setting all the negative elements of 1-2*A
to zero. The factors of 2 removed from each part of the equation result in a single factor of 4 multiplying the result, thus halving the number of element-wise multiplications you perform.
Even though you mention not wanting to rewrite the code, you might want to consider using a function or subfunction instead of an anonymous function if efficiency is key. Based on the results shown in this answer to a question about OOP timing, it appears that anonymous functions may have more overhead. And for such a short function, rewriting it wouldn't be that much work.