简体   繁体   English

Matlab函数句柄优化

[英]Matlab function handle optimizing

I have a function handle in Matlab like this 我在Matlab中有一个这样的函数句柄

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

Where A is typically a matrix. 其中A通常是矩阵。 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? 可以将其保留为函数句柄(因此我不必重写代码),但可以一劳永逸地计算2*A ,然后再应用3次?

Thanks in advance. 提前致谢。

First, one small quibble: you're not computing 2*A 3 times. 首先,有一个小问题:您没有计算2*A 3次。 You're computing it twice and computing 2*A.^5 once. 您计算两次,一次计算2*A.^5 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. 可以将其分解为(2*A).*A.^4 ,但是您可能不会节省很多工作。

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. 由于您仅限于匿名函数内部的单个表达式,因此在这种情况下,我认为没有特别干净或有效的方法可以预先计算2*A 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. 请注意,使用MAX进行的运算不会因将系数2移到运算之外而受影响,因为它只是将1-2*A所有负元素设置为零。 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. 从方程的每个部分中删除的因数2都会使结果乘以4的单个因数,从而使您执行的逐元素乘法的次数减半。

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. 根据此问题的答案所显示的结果, 有关OOP时序的问题似乎表明,匿名函数可能会有更多开销。 And for such a short function, rewriting it wouldn't be that much work. 对于这么短的功能,重写就不需要那么多的工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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