bsxfun - avoid the 'for' loop in matlab script by permuting -


i have code follows:

ne = 100; h = rand(ne,ne); g = zeros(ne,1);  e =1:ne     hue = h(:,e);     ss1 =  bsxfun(@times, hue', hue) .* m;   % m ne*ne matrix     g(e) = sum(ss1(:)); end 

when ne > 1000, runs slowly.

i read matlab documents, , find permute function possible way speed up. tried whole day , failed.

here code, , not know wrong.

c = permute(bsxfun(@times, permute(h, [1 3 2]), permute(h', [1 3 2])), [1 3 2]); g = sum(sum(c)) 

if math, you'll see have this:

g = sum(h) .^ 2; 

run speed: 0.000681 seconds, ne = 1000 (the original code took 3.047315 seconds).

edit:

now, edited code, have this:

g = diag(h.' * m * h); 

run speed: 0.072273 seconds, ne = 1000.

a speedup can obtained if notice if rearrange terms, can avoid second matrix multiplication (which changes dot product) , have sum columns, this:

g = sum(m.' * h .* h); 

run speed: 0.044190 seconds, ne = 1000.

it's idea math. spend time, code gains speedup. :)

note: run speeds measured averaging time of hundred runs.


Comments

Popular posts from this blog

apache - Remove .php and add trailing slash in url using htaccess not loading css -

javascript - jQuery show full size image on click -