While loop Vectorization

让人想犯罪 __ 提交于 2020-01-07 00:34:27

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/8283995/while-loop-vectorization

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!