0

I often end up trying to take a bunch of arrays and putting them in different dimensions as below,

x = x.reshape((x.size, 1, 1))
y = y.reshape((1, y.size, 1))
z = z.reshape((1, 1, z.size))

return x + y + z

I have two problems, I would like to do something like,

x = x.todim(0)
y = y.todim(1)
z = z.todim(2)

And achieve the same as above.

Also, I would like to do "tensor products" with different operators and have it be lazy evaluated because doing what I am doing often exploded the memory usage. But I do have a good reason for doing these kinds of things ... my insanity is justifiable.

EDIT:

Here is code I wrote to do it, but a built in would be nice is such exists

def todim(a, ndims, axis=0):
    nshape = [a.shape[i-axis]
              if i >= axis and (i-axis) < len(a.shape)
              else 1
              for i in range(ndims)]
    return a.reshape(tuple(nshape))

1 Answer 1

0

first, you are doing something similar to np.ix_.

In [899]: x,y,z=np.ix_(np.arange(3),np.arange(4),np.arange(5))
In [900]: x.shape,y.shape,z.shape
Out[900]: ((3, 1, 1), (1, 4, 1), (1, 1, 5))

numpy.lib.index_tricks.py has this and other indexing functions and classes.

A function like your todim could be:

 def todim(x,n,i):
    ind = [1]*n
    ind[i]=x.shape[0]
    return x.reshape(ind)

I'm not trying to make it a array method. A standalone function is easier. I also need to define the n, the target number of dimensions. np.ix_ does something like this.


To todim that you added (while I wrote my answer) is similar, but lets x have something other than 1d.

np.r_ takes an intial string argument that might allow similar specification.

x,y,z = np.r_['0,3,0',np.arange(3)], np.r_['0,3,1',np.arange(4)], np.r_['0,3,2',np.arange(5)]

produces the same 3 arrays as my initial ix_. It takes a string input, but you could easily insert numbers:

np.r_['0,%s,%s'%(3,1), np.arange(4)]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.