While循环矢量化 [英] While loop Vectorization

查看:140
本文介绍了While循环矢量化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有某种方式可以矢量化此代码.我竭尽全力...但是失败了.

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

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

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

推荐答案

通常,Matlab的向量化可在固定大小的数组/矩阵上运行.如果您想通过其他方式来加快代码执行速度,那么最大的一件事就是在循环的每次迭代中重用以前的结果,并摆脱无关的变量.

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

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

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

这篇关于While循环矢量化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆