简体   繁体   中英

Matlab function handle optimizing

I have a function handle in Matlab like this

fhandle = @(A) max(1-2*A,0).*(2*A.^5+2*A + 1)

Where A is typically a matrix. I perform this quite a few times and it is slowing down the computation. It is possible to keep it as a function handle (so I don't have to rewrite code) but to compute 2*A once and for all and then apply it the three times?

Thanks in advance.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM