Compute all differences possibilities in a vector

不想你离开。 提交于 2020-01-24 09:00:28

问题


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



来源:https://stackoverflow.com/questions/11623049/compute-all-differences-possibilities-in-a-vector

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!