1

I'm struggling with this code snippet using np.vectorize

def to_homogenous(x):
'''
Convert a point x to homogenous coordinates.
'''
return np.hstack((x,np.array([1]))).flatten()

vec_to_homo = np.vectorize(to_homogenous)
coords = vec_to_homo([0,1])

This results in the following Error:

ValueErrorTraceback (most recent call last)
in ()
----> 1 coords1 = vec_to_homo([0,1])

/home/lib/python2.7/site-packages/numpy/lib/function_base.pyc in call(self, *args, **kwargs)
2753 vargs.extend([kwargs[_n] for _n in names])
2754
-> 2755 return self._vectorize_call(func=func, args=vargs)
2756
2757 def _get_ufunc_and_otypes(self, func, args):

/home/lib/python2.7/site-packages/numpy/lib/function_base.pyc in _vectorize_call(self, func, args)
2832
2833 if ufunc.nout == 1:
-> 2834 res = array(outputs, copy=False, subok=True, dtype=otypes[0])
2835 else:
2836 res = tuple([array(x, copy=False, subok=True, dtype=t)

ValueError: setting an array element with a sequence.

I understand the error message but I cannot for the life of me find how I should change my function/the call to vectorize to solve this problem. The function yields correct results if I pass only a single integer, i.e. vec_to_homo(0) yields [0,1].

My snippet is very close to the example provided in the documentation linked above, so I really don't get what is going wrong.

Please help.
Thanks!

hsvar
  • 177
  • 4
  • 14
  • You don't say what you expect the `vectorized` result to be. To work with a function that returns an array, `vectorize` either needs `otypes=[object]` or a `signature` parameter. And passing anything other than scalars to your function requires the `signature`. Overall `vectorize` is an awkward crutch - occasionally useful, but easy to misuse. – hpaulj May 28 '18 at 21:02

1 Answers1

4

Your problem is as in this question. np.vectorize is only appropriate for functions that map floats to floats, not floats to Numpy arrays.

Additionally, np.vectorize does not speed up code execution. You can create your own logic inside the function to process a list and return a 2D array using comprehension, looping or similar.

twolffpiggott
  • 1,063
  • 8
  • 13