1

Is there a vectorized assigment of elements to sequences in numpy like in this discussion?

for instance:

xx = np.array([1,2], dtype=object)
expanded = np.arange(xx, xx+2)

instead of loops:

xx = np.array([1,2], dtype=object)
expanded = np.array([np.arange(x, x+2) for x in xx]).flatten()

This would be for mapping a scalar heuristic to the neighboring cells in a matrix that determined it (e.g. the range of cells that had the peak overlap from a correlation() operation).

Community
  • 1
  • 1
ecoe
  • 4,994
  • 7
  • 54
  • 72
  • 1
    Same thing, but without the flatten: http://stackoverflow.com/questions/40624409/creating-nd-arrays-with-different-rows; the problem is pretty easy as long as the length of the subranges is all the same. – hpaulj Nov 20 '16 at 23:59

1 Answers1

1

Like this?

>>> xx = np.array([3,8,19])
>>> (xx[:,None]+np.arange(2)[None,:]).flatten()
array([ 3,  4,  8,  9, 19, 20])

The xx[:,None] operation turns the length n vector into an nx1 matrix, and the np.arange(2)[None,:]) operation creates a length 1x2 matrix containing [0., 1.]. Added together using array broadcasting gives an nx2 matrix, which is then flattened into a length 2n vector.

Neapolitan
  • 2,101
  • 9
  • 21