How to vectorize an equation involving pair-wise distance computation, to improve the speed of computation?

1 回表示 (過去 30 日間)
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:
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".
Also, "j" represents the set of all elements in the vector field, except "i" . Hence, is the (u,v) vector for element "j".
Finally, and represent the 2-D co-ordinate location (x,y) for elements i and j respectively.
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

採用された回答

J. Alex Lee
J. Alex Lee 2020 年 8 月 21 日
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
  1 件のコメント
Tintumon
Tintumon 2020 年 8 月 26 日
Thank you a lot.
This idea helped me to eliminate the innermost "for loop".
And, Sorry for the late reply.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMathematics についてさらに検索

製品


リリース

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by