I am looking for a way to avoid for-loops in my code to keep computation times short.
k = rand(15,15)
v= rand(6,15)
for i=1:6
C(i) = v(i, :) * k * v(i, :)'
end
Is there such a possibility in this example, unfortunately I can't think of anything. In the real program v will not have only 6 lines, but thousands.
CodePudding user response:
The following will get you the same result. For medium-sized arrays (around 1.5k), this is 15X faster than the for
loop.
k = rand(15,15)
v = rand(6,15)
C = diag(v(1:6,:) * k * v(1:6,:)')'
A small benchmark as suggested by @Adriaan shows g()
is 17X faster:
k = rand(1500,1500);
v = rand(1000,1500);
f = @() fun(k,v);
g = @() diag(v(1:600,:) * k * v(1:600,:)')';
timeit(f) % Time: 0.5122
timeit(g) % Time: 0.0332
function C = fun(k,v)
C = zeros(1,600);
for i = 1:600
C(i) = v(i, :) * k * v(i, :)';
end
end
It should be made clear here that the for
loop is not to blame, but the underlying BLAS implementation for vector-matrix vs. matrix-matrix operations; the latter is known to be highly optimized in MKL.