Nested for loop performance speed up
조회 수: 2 (최근 30일)
이전 댓글 표시
Hi everybody,
I have this first version, working, of a analysis loop. This netsted for loop is simply analysing a geometric problem involving points.
The problem is, it is much too slow, as a big amount of points needs to be processed.
Previous calculation and assignment, causing the following vectors:
% Pre allocation/calculations
A = 3 x 8000
B = 3 x 1e6
% ....
% ....
% ....
C = [0;0;0];
alpha = 0;
beta = 0;
vis = 50;
D = zeros(size(B,2),size(A,2));
for i=1:size(A,2)
for k=1:size(B,2)
C = A(:,i) - B(:,k);
alpha = acos(dot(A(:,i),C)/norm(A(:,i))/norm(C));
beta = pi-acos(dot(B(:,k),C)/norm(B(:,k))/norm(C));
if((alpha <= (vis)) && beta >= pi/2)
D(k,i) = 1;
else
D(k,i) = 0;
end
end
end
Vectorizing this loop appears to be quite difficult, at least for me, e.g. because of the functions (dot product, norm etc,) beeing called within the loop. I got stuck here when trying to vectorize.
Are there any ideas or concrete approaches on your minds to inprove this loops' performance?
Thanks!
댓글 수: 1
Mario Malic
2021년 10월 12일
Hi,
dot allows entry of matrices, which would probably simplify and speed up the code as well. See the documentation how to properly call it.
답변 (1개)
Matt J
2021년 10월 12일
편집: Matt J
2021년 10월 12일
With the data sizes you've shown, the final result D will be a 7GB logical matrix. That seems like a non-starter. If you can reduce size(A,2) and size(B,2) to more practical values, however, then the loops can be vectorized as follows:
A=reshape(A,3,1,[])
C= A-B;
C=C./vecnorm(C,2,1);
A=A./vecnorm(A,2,1);
B=B./vecnorm(B,2,1);
alpha=squeeze( acos( sum(A.*C,1) ) );
beta=pi-squeeze( acos( sum(B.*C,1) ) );
D=alpha<=vis & beta>=pi/2;
댓글 수: 6
Bruno Luong
2021년 10월 12일
Ah I see. I would though for better speed, we do not need to call acos on huge array, but compare correlation instead.
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!