Nested for loop performance speed up

4 views (last 30 days)
Alexander Fuchs
Alexander Fuchs on 12 Oct 2021
Commented: Bruno Luong on 12 Oct 2021
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;
D(k,i) = 0;
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?
  1 Comment
Mario Malic
Mario Malic on 12 Oct 2021
dot allows entry of matrices, which would probably simplify and speed up the code as well. See the documentation how to properly call it.

Sign in to comment.

Answers (1)

Matt J
Matt J on 12 Oct 2021
Edited: Matt J on 12 Oct 2021
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:
C= A-B;
alpha=squeeze( acos( sum(A.*C,1) ) );
beta=pi-squeeze( acos( sum(B.*C,1) ) );
D=alpha<=vis & beta>=pi/2;
Bruno Luong
Bruno Luong on 12 Oct 2021
Ah I see. I would though for better speed, we do not need to call acos on huge array, but compare correlation instead.

Sign in to comment.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!