8

I have a Nx1 vector of values. 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. 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.

Luis Mendo
  • 110,752
  • 13
  • 76
  • 147
Jason Strimpel
  • 14,670
  • 21
  • 76
  • 106

3 Answers3

12

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__ =

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

).

Acorbe
  • 8,367
  • 5
  • 37
  • 66
7

meshgrid can generate matrices fit for this purpose. 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

>> 
Tim
  • 13,904
  • 10
  • 69
  • 101
0

Nice answers given already. But to join in the fun, here is another way (using Tim data)

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
Nasser
  • 12,849
  • 6
  • 52
  • 104