Matlab函数句柄优化

发布于 2024-11-08 19:55:28 字数 220 浏览 0 评论 0原文

我在 Matlab 中有一个像这样的函数句柄

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

其中 < code>A 通常是一个矩阵。我执行了很多次,它减慢了计算速度。可以将其保留为函数句柄(这样我就不必重写代码),但一劳永逸地计算 2*A 然后应用它三次?

提前致谢。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

柠檬色的秋千 2024-11-15 19:55:28

首先,有一个小问题:您没有计算 2*A 3 次。您计算了两次并计算了一次2*A.^5。请注意,幂运算符优先于乘法运算符。您可以将其分解为(2*A).*A.^4,但您可能不会为自己节省太多工作。

由于您仅限于 匿名函数 中的单个表达式,在这种情况下,我没有想到特别干净或有效的方法来预先计算 2*A 。相反,您可以将乘法因子移到括号之外,以减少执行的乘法量。您可以按如下方式重写方程式:

fhandle = @(A) 4.*max(0.5 - A,0).*(A.^5 + A + 0.5);

请注意,您的操作使用 MAX将因子 2 移到运算之外不会受到影响,因为它只是将 1-2*A 的所有负元素设置为零。从方程的每个部分中删除的因子 2 会导致结果乘以一个因子 4,从而使您执行的逐元素乘法的数量减半。

即使您提到不想重写代码,您也可能需要考虑使用 函数子函数 而不是匿名函数。基于 中显示的结果这个关于 OOP 计时问题的答案,看来匿名函数可能有更多的开销。对于这么短的函数,重写它并不需要那么多工作。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文