2010-03-19 190 views
4

我使用pdist命令查找x和存儲在一個矩陣y座標之間的距離。MATLAB pdist功能

X = [100 100; 
     0 100; 
    100 0; 
    500 400; 
    300 600;]; 

D = pdist(X,'euclidean') 

它返回一個15元素的向量。 :

[0.734979755525412 3.40039811339820 2.93175207511321 1.83879677592575 2.40127440268306 2.75251513299386 2.21488402640753 1.10610649500317 1.81674017301699 0.903207751535635 1.99116952754924 1.05069952386082 1.24122819418333 1.08583377275532 1.38729428638035] 

有沒有辦法將這些距離與他們從來源的座標,即它們存儲在與一般的行形成矩陣相關聯:

[Length xcoordinate1 ycoordinate1 xcoordinate2 ycoordinate2] 

哪裏有一排各發現長度?

在此先感謝

+0

你的例子是否正確?我得到了一個10 *元素的*非常*不同的值。 – gnovice 2010-03-19 15:39:25

+2

你可能會發現有用的另一個功能是SQUAREFORM http://www.mathworks.com/access/helpdesk/help/toolbox/stats/squareform.html – Amro 2010-03-19 20:05:41

回答

7
%# define X, D 
X = [100 100; 
     0 100; 
    100 0; 
    500 400; 
    300 600;]; 

D = pdist(X,'euclidean'); 

%# find the indices corresponding to each distance 
tmp = ones(size(X,1)); 
tmp = tril(tmp,-1); %# creates a matrix that has 1's below the diagonal 

%# get the indices of the 1's 
[rowIdx,colIdx ] = find(tmp); 

%# create the output 
out = [D',X(rowIdx,:),X(colIdx,:)]; 
1

您可以使用函數NCHOOSEK生成一組指標爲X,建立自己的矩陣方式如下:

>> X = [100 100; 0 100; 100 0; 500 400; 300 600]; %# Your sample data 
>> D = pdist(X,'euclidean')' %'# Euclidean distance, with result transposed 

D = 

    100.0000 %# Note that I get different results than your example! 
    100.0000 
    500.0000 
    538.5165 
    141.4214 
    583.0952 
    583.0952 
    565.6854 
    632.4555 
    282.8427 

>> index = nchoosek(1:size(X,1),2); 
>> M = [D X(index(:,1),:) X(index(:,2),:)] %# [Distance X1 Y1 X2 Y2] 

M = 

    100.0000 100.0000 100.0000   0 100.0000 
    100.0000 100.0000 100.0000 100.0000   0 
    500.0000 100.0000 100.0000 500.0000 400.0000 
    538.5165 100.0000 100.0000 300.0000 600.0000 
    141.4214   0 100.0000 100.0000   0 
    583.0952   0 100.0000 500.0000 400.0000 
    583.0952   0 100.0000 300.0000 600.0000 
    565.6854 100.0000   0 500.0000 400.0000 
    632.4555 100.0000   0 300.0000 600.0000 
    282.8427 500.0000 400.0000 300.0000 600.0000 

注意函數NCHOOSEK會僅是一個實用的解決方案,如果在X列的數目是小於約15

編輯:因爲pdist選擇成對的點,使秒針參數nchoosek應該簡單地2。它獨立於數據的維度。這也使得前一行的註釋變得過時。 (對不起,編輯這種方式,沒有足夠的代表添加評論,但我真的很喜歡這個答案,並想修復它) - 保羅

12

MATLAB有一個內置的命令稱爲「方形」,將pdist輸出轉換爲一個nxn距離矩陣http://www.kxcad.net/cae_MATLAB/toolbox/stats/pdist.html

%# define X, D 
X = [100 100; 
     0 100; 
     100 0; 
    500 400; 
    300 600;]; 

D = squareform(pdist(X,'euclidean')); 
+0

只是爲了蟒蛇用戶誰見了同樣的問題發表評論。在SciPy的,你也可以使用'squareform'到pdist'的'結果等轉換成方形陣列。這些函數可以在'scipy.spatial.distance'中找到。比照[此篇](http://stackoverflow.com/questions/13079563/how-does-condensed-distance-matrix-work-pdist) – 2015-12-28 09:54:42