-1

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 Python's vectorization capabilities as this vector may get quite large. I realize there are a few questions out there with abstract answers.

How can I replicate MATLAB's bsxfun function in Python?

I posted a question on SE to discover the bsxfun here, but now need to do the same in Python.

Community
  • 1
  • 1
Jason Strimpel
  • 14,670
  • 21
  • 76
  • 106
  • Did you even try [searching](http://stackoverflow.com/questions/8946810/is-there-an-equivalent-to-the-matlab-function-bsxfun-in-python)? – danodonovan Feb 18 '13 at 17:09
  • Yes, read http://stackoverflow.com/questions/8946810/is-there-an-equivalent-to-the-matlab-function-bsxfun-in-python, http://stackoverflow.com/questions/12454685/translating-a-line-of-matlab-bsxfun-rdivide-to-python, and the broadcasting tutorial here http://www.scipy.org/EricsBroadcastingDoc, did you really need to downvote? You didn't even post a response. – Jason Strimpel Feb 18 '13 at 17:14

1 Answers1

3

I'm not entirely clear on what you want, but numpy's broadcasting rules (see here for an introduction) mean that most of the time bsxfun isn't needed because it Just Works(tm). For example, if I understand what you're getting at, something like

>>> a = np.array([1,3,5,7,9])
>>> a - a[:,None]
array([[ 0,  2,  4,  6,  8],
       [-2,  0,  2,  4,  6],
       [-4, -2,  0,  2,  4],
       [-6, -4, -2,  0,  2],
       [-8, -6, -4, -2,  0]])

should work.

DSM
  • 342,061
  • 65
  • 592
  • 494