我正在尝试优化这段代码并摆脱实现的嵌套循环。我发现将矩阵应用于pdist函数存在困难
例如,1 + j // -1 + j // -1 + j // -1-j是初始点,我试图通过最小距离逼近点检测0.5 + 0.7j 。
任何帮助表示赞赏
function result = minDisDetector( newPoints, InitialPoints)
result = [];
for i=1:length(newPoints)
minDistance = Inf;
for j=1:length(InitialPoints)
X = [real(newPoints(i)) imag(newPoints(i));real(InitialPoints(j)) imag(InitialPoints(j))];
d = pdist(X,'euclidean');
if d < minDistance
minDistance = d;
index = j;
end
end
result = [result; InitialPoints(index)];
end
end
答案 0 :(得分:4)
您可以使用Speed-efficient classification in Matlab
中列出的有效欧几里德距离计算 vectorized solution
-
%// Setup the input vectors of real and imaginary into Mx2 & Nx2 arrays
A = [real(InitialPoints) imag(InitialPoints)];
Bt = [real(newPoints).' ; imag(newPoints).'];
%// Calculate squared euclidean distances. This is one of the vectorized
%// variations of performing efficient euclidean distance calculation using
%// matrix multiplication linked earlier in this post.
dists = [A.^2 ones(size(A)) -2*A ]*[ones(size(Bt)) ; Bt.^2 ; Bt];
%// Find min index for each Bt & extract corresponding elements from InitialPoints
[~,min_idx] = min(dists,[],1);
result_vectorized = InitialPoints(min_idx);
快速运行时测试,newPoints
为400 x 1
&amp; InitialPoints
为1000 x 1
:
-------------------- With Original Approach
Elapsed time is 1.299187 seconds.
-------------------- With Proposed Approach
Elapsed time is 0.000263 seconds.
答案 1 :(得分:0)
解决方案非常简单。但是,您确实需要我的cartprod.m function来生成笛卡尔积。
首先为每个变量生成随机复杂数据。
newPoints = exp(i * pi * rand(4,1));
InitialPoints = exp(i * pi * rand(100,1));
使用newPoints
生成InitialPoints
和cartprod
的笛卡尔积。
C = cartprod(newPoints,InitialPoints);
第1列和第2列的差异是复数的距离。然后abs
将找到距离的大小。
A = abs( C(:,1) - C(:,2) );
由于生成了笛卡尔积,因此它首先排列newPoints
个变量:
1 1
2 1
3 1
4 1
1 2
2 2
...
我们需要reshape
它并使用min
获得最小距离以找到最小距离。我们需要转置来找到每个newPoints
的最小值。否则,如果没有转置,我们将获得每个InitialPoints
的最小值。
[m,i] = min( reshape( D, length(newPoints) , [] )' );
m
为您提供分数,而i
则为您提供分数。如果您需要获得最低initialPoints
,请使用:
result = initialPoints( mod(b-1,length(initialPoints) + 1 );
答案 2 :(得分:0)
通过使用欧几里德范数引入逐元素运算来计算距离,可以消除嵌套循环。如下所示。
result = zeros(1,length(newPoints)); % initialize result vector
for i=1:length(newPoints)
dist = abs(newPoints(i)-InitialPoints); %calculate distances
[value, index] = min(dist);
result(i) = InitialPoints(index);
end