matlab - Vectorizing in Multiple Dimensions -
i have following loop in matlab code i'd rid of:
for i=1:size(thepolygon,3) activevalues(:,i) = sum(normalvectors.*thepolygon(:,:,i),2); checkvalues(:,i) = sign(activevalues(:,i)-sum(normalvectors.*thepolygon3(:,:,i),2)); end i tried replacing i 1:size(thepolygon,3), dimensions don't line element-by-element multiplication, , i'm not sure else try. in advance tips.
it's difficult test without example data but:
activevalues = squeeze(sum(bsxfun(@times, normalvectors, thepolygon), 2)) ok first test data:
a = rand(3,3,3); b = rand(3,3); now test yours
for i=1:size(a,3) c(:,i) = sum(b.*a(:,:,i),2); end on run got:
c = 0.9773 1.0608 0.3673 0.6670 0.1597 0.7296 0.8372 1.1418 0.9828 and mine:
squeeze(sum(bsxfun(@times, b, a), 2)) i get
ans = 0.9773 1.0608 0.3673 0.6670 0.1597 0.7296 0.8372 1.1418 0.9828 so assuming mine correct.
explanation:
bsxfun(@times, b, a) broadcasting, expands b along it's singleton dimension (in case dim 3) match size of a , applies function (@times .*) element element expanded b , a. identical (but better practice , faster) going repmat(b, [1 1 size(a,3)]).*a.
then sum 3d matrix column wize have, i.e. sum(x, 2) returns 1x3x3 result. want 3x3 result rid of singelton dimension (i.e. dim 1 equals 1) used squeeze
it should trivial vectorize second line in same way.
but
tic; k = 1:10000 c = squeeze(sum(bsxfun(@times, b, a), 2)); end; toc elapsed time 0.394828 seconds. tic; c = zeros(3,3); k = 1:10000 i=1:size(a,3) c(:,i) = sum(b.*a(:,:,i),2); end; end; toc elapsed time 0.113199 seconds. the non-vectorized code faster in matlasb 2012b!!!!!!!
Comments
Post a Comment