While 循环向量化

发布于 2024-12-18 08:27:02 字数 462 浏览 3 评论 0原文

我想知道是否有某种方法可以向量化这段代码。我很努力地去做……但失败了。

while (delta_F > e) && (i < maxLoop)      
    x1 = x0+d;
    y0 = f(x0);
    y1 = f(x1);
    if y1 < y0
        x0= x1;
        d = a*d;
    else
        vF = [vF;x1];
        d = -b*d;
    end
    i = i + 1;
    if length(vF) > 1
        ultm = vF(end);
        pultm = vF(end-1);
        delta_F = abs(ultm+pultm)/2;
    end
end

这是 Rosenbrock 方法的简单实现,用于查找函数的最小值。

I would like to know if there is some way to vectorize this code. I tried so hard to do it... but failed.

while (delta_F > e) && (i < maxLoop)      
    x1 = x0+d;
    y0 = f(x0);
    y1 = f(x1);
    if y1 < y0
        x0= x1;
        d = a*d;
    else
        vF = [vF;x1];
        d = -b*d;
    end
    i = i + 1;
    if length(vF) > 1
        ultm = vF(end);
        pultm = vF(end-1);
        delta_F = abs(ultm+pultm)/2;
    end
end

It's a simple implementation of the Rosenbrock method for finding the min of a function.

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

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

发布评论

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

评论(1

哆兒滾 2024-12-25 08:27:02

一般来说,Matlab 的矢量化适用于固定大小的数组/矩阵。如果您想以其他方式加速此代码,您可以做的最重要的事情就是在循环的每次迭代中重用以前的结果并摆脱无关的变量。

y0 = f(x0);
while (delta_F > e) && (i < maxLoop)
    x1 = x0+d;
    y1 = f(x1);
    if (y1 < y0) %# new starting point, so swap points
        x0 = x1;
        y0 = y1; 
        d = a*d;
    else         %# same starting point, refine step and see if we're done
        d = -b*d;
        delta_F = abs(x1-x0)/2;
    end
    i = i+1;
end

这消除了一半对 f 的调用以及 vF 的动态调整大小,这非常慢,尤其是当 vF 变大时。

In general, Matlab's vectorization works over fixed-size arrays/matrices. If you want to speed up this code in some other ways, the single biggest thing you could do is reuse your previous results in each iteration of the loop and get rid of the extraneous variables.

y0 = f(x0);
while (delta_F > e) && (i < maxLoop)
    x1 = x0+d;
    y1 = f(x1);
    if (y1 < y0) %# new starting point, so swap points
        x0 = x1;
        y0 = y1; 
        d = a*d;
    else         %# same starting point, refine step and see if we're done
        d = -b*d;
        delta_F = abs(x1-x0)/2;
    end
    i = i+1;
end

This removes half the calls to f and the dynamic resizing of vF, which is horrendously slow, especially as vF gets big.

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