What is wrong with the following code for computing distance between all pairs of vectors?
<p>I'm trying to find manhattan distance between all pairs of vectors.</p>

<pre><code>import numpy as np
import itertools

class vector:
    def __init__(self):
        self.a = 0
        self.b = 0

c = vector()
d = vector()
l = vector()
m = vector()

e = [c,d]
n = [l,m]
o = np.array(n)
f = np.array(e)
p = itertools.product(o,f)
p = list(p)
def comp(x):
    return (x[0].a-x[1].a) + (x[0].b-x[1].b)

g = np.vectorize(comp)
print g(p)
</code></pre>

<p>I get the error:</p>

<pre><code>Traceback (most recent call last):
  File "&lt;stdin&gt;", line 1, in &lt;module&gt;
  File "/usr/local/lib/python2.7/site-packages/numpy/lib/function_base.py", line 2207, in __call__
    return self._vectorize_call(func=func, args=vargs)
  File "/usr/local/lib/python2.7/site-packages/numpy/lib/function_base.py", line 2270, in _vectorize_call
    ufunc, otypes = self._get_ufunc_and_otypes(func=func, args=args)
  File "/usr/local/lib/python2.7/site-packages/numpy/lib/function_base.py", line 2232, in _get_ufunc_and_otypes
    outputs = func(*inputs)
  File "&lt;stdin&gt;", line 2, in comp
AttributeError: vector instance has no attribute '__getitem__'
</code></pre>

<p>I have to say I'd approach this differently. Numerical Python doesn't deal well with Python classes and such.</p>

<p>Your class</p>

<pre><code>class vector:
    def __init__(self):
        self.a = 0
        self.b = 0
</code></pre>

<p>Is basically a length-2 vector. So, if you're going to operate on many length-2 vectors, I'd suggest something like this:</p>

<pre><code>In [13]: p = np.array([[1, 2], [3, 4], [5, 6]])

In [14]: p
Out[14]: 
array([[1, 2],
       [3, 4],
       [5, 6]])
</code></pre>

<p>Each row is a length-2 vector. There are 3 such vectors. This is far far far more efficient than a Python <code>list</code> of Python classes.</p>

<p>Now your <code>comp</code> function</p>

<pre><code>def comp(x):
    return (x[0].a-x[1].a) + (x[0].b-x[1].b)
</code></pre>

<p>is basically equivalent to</p>

<pre><code>def comp(x):
    return (x[0].a+x[0].b) - (x[1].a+x[1].b)
</code></pre>

<p>i.e., the component sum of the first vector, minus the component sum of the second vector. That being the case, you can efficiently calculate the pairwise outputs via</p>

<pre><code>In [15]: q = p.sum(axis=1)
</code></pre>

<p>for calculating the component sum of each vector, followed by</p>

<pre><code>In [16]: np.subtract.outer(q, q)
Out[16]: 
array([[ 0, -4, -8],
       [ 4,  0, -4],
       [ 8,  4,  0]])
</code></pre>

python vectorization itertools