While 循环向量化
我想知道是否有某种方法可以向量化这段代码。我很努力地去做……但失败了。
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
一般来说,Matlab 的矢量化适用于固定大小的数组/矩阵。如果您想以其他方式加速此代码,您可以做的最重要的事情就是在循环的每次迭代中重用以前的结果并摆脱无关的变量。
这消除了一半对
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.
This removes half the calls to
f
and the dynamic resizing ofvF
, which is horrendously slow, especially asvF
gets big.