Matlab代码优化和消除循环
我无法自己删除这个循环,如果有人可以帮助我优化这段代码 - 欢迎。
M = length(w);
expt = exp(-t .* (phis * w'));
G = zeros(M, M);
for i = 1 : M
for j = 1 : M
last = 2 * reg_coef * eye(M);
G(i,j) = last(i, j) + mean(expt .* t .^2 .* phis(:,i) .* phis(:,j) ./ (1 + expt) .^ 2);
end
end
- w - 尺寸为 (1xM)
- phis - 尺寸为 (NxM)
- t - 尺寸为 (Nx1)
I can't remove this loops by myself, if anybody can help me with optimization this piece of code - welcome.
M = length(w);
expt = exp(-t .* (phis * w'));
G = zeros(M, M);
for i = 1 : M
for j = 1 : M
last = 2 * reg_coef * eye(M);
G(i,j) = last(i, j) + mean(expt .* t .^2 .* phis(:,i) .* phis(:,j) ./ (1 + expt) .^ 2);
end
end
- w - size is (1xM)
- phis - size is (NxM)
- t - size is (Nx1)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
通过编写更清晰的代码,您可以做得更好 - 确保正确分配,确保从循环中删除重复计算等:
编辑:您还可以看到生成的矩阵 G 是对称的,因此您通过仅计算上三角形并随后作为转置填充下三角形,即可立即获得
2x
加速。至少在我的
MATLAB
中,通过使用临时数组对mean()
调用进行矢量化,可以实现另一个大幅加速。对于此
100x100
情况,我的计算机上的加速约为41.0
。希望这有帮助。
You can do alot better by just writing cleaner code - ensure that you allocate properly, ensure that you remove duplicate calculations from loops etc:
EDIT: You can also see that the resulting matrix
G
is symmetric, so you get an immediate2x
speed-up by only calculating the upper triangle and filling in the lower triangle afterwards as a transpose.At least with my
MATLAB
another big speed-up is achieved by vectorising the call tomean()
through the use of a temporary array.For this
100x100
case the speed-up was around41.0
on my machine.Hope this helps.
您至少可以从循环中取出很多术语:
You can, at least, take a lot of terms out of the loops: