Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

arrays - MATLAB: Matrix of pairwise differences

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...