A way to avoid for-loops in this example

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.

>Solution :

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)
    for i = 1:600
        C(i) = v(i, :) * k * v(i, :)';
    end
end

Leave a Reply