MATLAB Answers

vectorize a for loop

1 view (last 30 days)
Marko
Marko on 21 Apr 2021
Edited: Marko on 21 Apr 2021
Hello Community,
i need ur help, to speed up a routine.
i have n points in space and i need the distances between all points.
Here is the primitve script: ( n is normally some in the range of 1e5...)
n = 8;
xc = rand(n,1);
yc = rand(n,1);
r = zeros(n);
for i = 1:n
for j=1:n
if i~=j
r(i,j) = sqrt((xc(i)-xc(j))^2 + (yc(i)-yc(j))^2);
end
end
end
I know that the matrix r is symmetic so i need only to compute half of the elements. (This speed up to 50%)
n = 8;
xc = rand(n,1);
yc = rand(n,1);
r = zeros(n);
for i = 1:n
for j=1:n
if and(i~=j,i<j)
r(i,j) = sqrt((xc(i)-xc(j))^2 + (yc(i)-yc(j))^2);
end
end
end
toc
r = (r+r');
But it is possible to vectorize the whole routine?
Maybe with permute and a adjoint matrix which could be vectorised A(:) = ....
Thank you in Advance!
  2 Comments
Marko
Marko on 21 Apr 2021
Hello Matt,
sorry there is a mistake n should be in the order of 1e3!
I am writing a panel method, and estimatet the max. number of n-panels for an multi element airfoil.
So the Ram should not be the limiting factor.

Sign in to comment.

Accepted Answer

Matt J
Matt J on 21 Apr 2021
Edited: Matt J on 21 Apr 2021
This should be pretty well optimized already,
r=pdist([xc,yc]);
  4 Comments
Marko
Marko on 21 Apr 2021
perfect, thank you Matt!

Sign in to comment.

More Answers (0)

Products

Community Treasure Hunt

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

Start Hunting!