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)
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
Gis symmetric, so you get an immediate2xspeed-up by only calculating the upper triangle and filling in the lower triangle afterwards as a transpose.At least with my
MATLABanother big speed-up is achieved by vectorising the call tomean()through the use of a temporary array.For this
100x100case the speed-up was around41.0on my machine.Hope this helps.