简体   繁体   English

MATLAB:成对差异矩阵

[英]MATLAB: Matrix of pairwise differences

I have a Nx1 vector of values. 我有一个值的Nx1向量。 What I would like to do is create a NxN matrix where each value represents the difference between the ith and jth value - sort of like a large correlation matrix. 我想做的是创建一个NxN矩阵,其中每个值代表ith和jth值之间的差-有点像一个大的相关矩阵。 I've done with this with a loop but I'm looking for a more elegant way to approach using MATLAB's vectorization capabilities as this vector may get quite large. 我已经完成了一个循环,但是我正在寻找一种更优雅的方法来使用MATLAB的矢量化功能,因为此矢量可能会变得很大。

what about 关于什么

    diff__ = bsxfun(@minus,repmat(A,N,1),A');

which can be definitely improved by doing 通过这样做绝对可以改善

    diff__ = bsxfun(@minus,A,A');

?

A little performance check: 性能检查:

   N = 1000;
   v = rand(N,1);

   tic
   diff__ = bsxfun(@minus,repmat(v,N,1),v');
   toc

   tic
   diff__ = bsxfun(@minus,v,v');
   toc

result 结果

  Elapsed time is 105.343344 seconds.
  Elapsed time is 1.124946 seconds.

(Tim's data check: (蒂姆的数据检查:

diff__ = diff__ =

 0     2     6     4
-2     0     4     2
-6    -4     0    -2
-4    -2     2     0

). )。

meshgrid can generate matrices fit for this purpose. meshgrid可以生成适合此目的的矩阵。 Obtain the difference matrix with 获得差矩阵

meshgrid(v) - meshgrid(v)'

Example: 例:

>> v = [1 3 7 5]

v =

     1     3     7     5

>> meshgrid(v)

ans =

     1     3     7     5
     1     3     7     5
     1     3     7     5
     1     3     7     5

>> meshgrid(v) - meshgrid(v)'

ans =

     0     2     6     4
    -2     0     4     2
    -6    -4     0    -2
    -4    -2     2     0

>> 

Nice answers given already. 已经给出了不错的答案。 But to join in the fun, here is another way (using Tim data) 但是要享受乐趣,这是另一种方式(使用Tim数据)

v=[1 3 7 5];
 cell2mat(arrayfun(@(i) (v(i)-v)',1:size(v,2), 'UniformOutput',false))

ans = 回答=

 0     2     6     4
-2     0     4     2
-6    -4     0    -2
-4    -2     2     0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM