Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading