2017-03-15 7 views
1

私は5点の幾何学座標を含む行列を持っています。ループなしの行列演算

centroids = [x1,x2;...;x5,y5] 

他のすべての点と距離を含む行列を作成したいと思います。

distance = 

    inf   pt1-pt2  pt1-pt3  pt1-pt4  pt1-pt5 
    pt2-pt1  inf   pt2-pt3  pt2-pt4  pt2-pt5 
    pt3-pt3  pt3-pt2  inf   pt3-pt4  pt3-pt5 
    pt4-pt1  pt4-pt2  pt4-pt3  inf   pt4-pt5 
    pt5-pt1  pt5-pt2  pt5-pt3  pt5-pt4  inf 

、私は[値、インデックス] =分(距離(...))は、各ラインの指標と分をしたいので、私は、INFを使用します。

objectifは、このような最終行列持つことです:私はループでこれを行うために達成

result = 
    indice_of_the_closest  dist 
    indice_of_the_closest  dist 
    indice_of_the_closest  dist 
    indice_of_the_closest  dist 
    indice_of_the_closest  dist 

を私はループせずにこれを行うにはいくつかの助けを必要としています。あなたは、統計ツールボックスを持っていない場合は、統計ツールボックスを持っている場合

敬具

答えて

3

は、あなたが最も近い見つけるためにknnsearchを使用することができ、この

% Compute the pair-wise distances 
d = sqrt((x(:,1) - x(:,1).').^2 + (x(:,2) - x(:,2).').^2); 

% If you are on MATLAB < 2016b 
% d = sqrt(bsxfun(@minus, x(:,1), x(:,1).').^2 + bsxfun(@minus, x(:,2), x(:,2).').^2); 

% Set the diagonal to Inf 
d(logical(eye(size(d)))) = Inf; 

% Find the minimum distance and index 
[mindist, ind] = min(d, [], 1); 

% Create the output matrix 
result = [ind(:), mindist(:)]; 

ような何かを行うことができます2つのが各ポイントを指します(最初の最も近いポイントはポイントそのものです)

[inds, dists] = knnsearch(x, x, 'k', 2); 
result = [inds(:,2), dists(:,2)]; 
+0

MATLAB <2016bのソリューションについて詳しく教えてください。 私は正確に理解できません。ありがとう – gpbdr13

関連する問題