Bartlomiej Lewandowski
Bartlomiej Lewandowski

Reputation: 11170

Create distance matrix from the result of pdist

I would like to create a matrix from the result of pdist. pdist returns a vector of distances: 1-2, 1-3, 1-4.. 2-3.. etc.

i have tried to use this as suggested to get the upper triangle:

a = [1,2,3,4,5,6,7,8,9,10]
b=triu(ones(5),1);
b(b==1)=a;

but this returns

0     1     2     4     7 
0     0     3     5     8
0     0     0     6     9
0     0     0     0    10
0     0     0     0     0

Is there a oneliner/function to do this correctly?

Upvotes: 2

Views: 1354

Answers (1)

yuk
yuk

Reputation: 19870

As I understand from the title you want to create a square matrix from PDIST function result. It can be easily done with SQUAREFORM function. And it works in both directions.

a = pdist(...);
asq = squareform(a);

Upvotes: 3

Related Questions