matlabeuclidean-distancepdist

How to separately compute the Euclidean Distance in different dimension?


I got a question when using pdist, it would be so many thanks if you could give me some advice. The pdist(D) usually gives the sum of the distance for the multiple dimension, however, I want to get the distance separately. For example I have a data set S which is a 10*2 matrix , I am using pdist(S(:,1)) and pdist(S(:,2)) to get the distance separately, but this seems very inefficient when the data has many dimensions. Is there any alternative way to achieve this more efficient? Thanks in advance!


Solution

  • Assuming you just want the absolute difference between the individual dimensions of the points then pdist is overkill. You can use the following simple function

    function d = pdist_1d(S)
        idx = nchoosek(1:size(S,1),2);
        d = abs(S(idx(:,1),:) - S(idx(:,2),:));
    end
    

    which returns the absolute pairwise difference between all pairs of rows in S.

    In this case

    dist = pdist_1d(S)
    

    gives the same result as

    dist = cell2mat(arrayfun(@(dim)pdist(S(:,dim))',1:size(S,2),'UniformOutput',false));