Vectorization of nested for loops for following code
Show older comments
Can someone please help me to vectorize following code to avoid for loops. A similar kind of code is being called in one of my program too many times, hence need to optimize for efficiency purpose. Note that I don't want to use sum() or mean2() function as those are resulting efficiency reduction (at least when matrix size is 2x2). Thanks
Code :
rangeDim = 4;
domainDim = 2*rangeDim;
dDomain = double(randi(10,domainDim));
reducedDomain = double(zeros(rangeDim, rangeDim));
for i=1:rangeDim
i2 = i*2;
for j=1:rangeDim
j2 = j*2;
reducedDomain(i,j) = 0.25*(dDomain(i2-1,j2-1)+dDomain(i2-1,j2)+dDomain(i2,j2-1)+dDomain(i2,j2));
%reducedDomain(i,j) = mean2(dDomain(i2-1:i2,j2-1:j2));
%reducedDomain(i,j) = 0.25*sum(sum(dDomain(i2-1:i2,j2-1:j2)));
end
end
1 Comment
Matt J
on 9 Dec 2015
A similar kind of code is being called in one of my program too many times, hence need to optimize for efficiency purpose
Vectorizing operations on small chunks of data isn't going to be very beneficial. What you really want is to vectorize the outer loop, the one that performs this operation "many times".
Accepted Answer
More Answers (3)
reducedDomain=sepblockfun(dDomain,[2,2],'mean');
or
reducedDomain=sepblockfun(dDomain,[2,2],'sum')/4;
Alan Weiss
on 9 Dec 2015
0 votes
- Why all the double calls? It seems to me that they are completely superfluous.
- MATLAB is a matrix language. I believe that you can find a matrix A so that reducedDomain = A*dDomain or something similar.
- It is possible that conv2 could help.
Alan Weiss
MATLAB mathematical toolbox documentation
I realized that sepblockfun() works with better efficiency for large size matrix, where as conv2() is performing better in average case.
That would be because sepblockfun has overhead from M-coded pre-checks and argument parsing that it performs in addition to the actual computation. However, you can customize the key lines from sepblockfun to this particular computation as below. I'm finding that this outperforms the conv2 approach even for rangeDim as small as 4.
rangeDim = 4;
domainDim = 2*rangeDim;
dDomain = randi(10,domainDim);
N=10000;
tic;
for i=1:N
X=reshape(dDomain,2,rangeDim,2,rangeDim);
reducedDomain=reshape(sum(sum(X,1),3),rangeDim,rangeDim)/4;
end
toc
%Elapsed time is 0.027305 seconds.
tic;
for i=1:N
reducedDomain = 0.25*conv2(dDomain, ones(2), 'valid');
reducedDomain = reducedDomain(1:2:end, 1:2:end);
end
toc
%Elapsed time is 0.050848 seconds.
1 Comment
Ashish KL
on 11 Dec 2015
Categories
Find more on Logical in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!