How to vectorize an equation involving pair-wise distance computation, to improve the speed of computation?
1 view (last 30 days)
Show older comments
Let me explain the situation, first:
I have a vector field, where each element has a:
1) 2-D co-ordinate location (x,y)
2) 2-D vector u,v (where u and v represents the displacements in x and y directions respectively)
I am trying to implement the following equation over this vector field:
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/349634/image.png)
where,
V' is the new vector field after applying the equation to the input vector field V. Therefore,
is the updated (u,v) vector value for the element "i".
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/349637/image.png)
Also, "j" represents the set of all elements in the vector field, except "i" . Hence,
is the (u,v) vector for element "j".
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/349640/image.png)
Finally,
and
represent the 2-D co-ordinate location (x,y) for elements i and j respectively.
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/349643/image.png)
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/349646/image.png)
I have done the following implementation (say, for 100 elements). But, it takes a lot of time to execute when the number of elements increases.
Can you help me to vectorize it, if possible?
% the variable "xyuv" contains:
% xyuv(i,1) : x-coordinate for i-th particle
% xyuv(i,2) : y-coordinate for i-th particle
% xyuv(i,3) : u-value for i-th particle
% xyuv(i,4) : v-value for i-th particle
for i=1:100 %total 100 elements
sum_temp = 0;
for j=1:100
if(j~=i) %to avoid i-vs-i computation, in order to speed up
if((1-pdist2(xyuv(i,3:4),xyuv(j,3:4),'cosine'))>=0.8) % if the condition is sastified, then do summation
term_2 = exp(-1*(pdist2(xyuv(i,1:2),xyuv(j,1:2)))); %second term of the equation
term_3 = exp(-1*abs(dot(xyuv(j,3:4), (xyuv(i,1:2)-xyuv(j,1:2))))); %third term of the equation
sum_temp = sum_temp + xyuv(j,3:4)*term_2*term_3; % summation
end
end
end
new_V(i,:) = sum_temp; % updated vector for element i
end
0 Comments
Accepted Answer
J. Alex Lee
on 21 Aug 2020
I think you should be able to loop only once over the reference point i, then take then compute difference vectorially.
Also, indexing can be "expensive", so perhaps better to split before the loop
xy = xyuv(:,1:2);
uv = xyuv(:,3:4);
for i = 1:N
dxy = xy(i,:) - xy
% not sure what the overhead is like for pdist2, or if it is vectorized, but
d = sqrt(dxy.*dxy); % right?
% etc
end
More Answers (0)
See Also
Categories
Find more on Creating and Concatenating Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!