Compute all differences possibilities in a vector

2019-07-07 07:44发布

问题:

Let's say I have a short vector x = [a,b,c,d,e]; What would be the best way to compute all the difference between members of the vector as:

y = [e-d e-c e-b e-a
     d-e d-c d-b d-a
     c-e c-d c-b c-a
     b-e b-d b-c b-a
     a-e a-d a-c a-b];

Thanks in advance

回答1:

To give that exact matrix, try:

x = [1;2;3;4;5];     %# note this is a column vector (matrix of rows in general)

D = squareform( pdist(x,@(p,q)q-p) );
U = triu(D);
L = tril(D);
y = flipud(fliplr( L(:,1:end-1) - U(:,2:end) ))

result in this case:

y =
     1     2     3     4
    -1     1     2     3
    -2    -1     1     2
    -3    -2    -1     1
    -4    -3    -2    -1


回答2:

First creat a circulant matrix, then compute the different between the first column and the rest columns. Here is a reference for creating a circulant matrix