0

I have two arrays

x * 2
x * 4

where

x = np.ones([5,4],int)

I want to create an array U such that

U = np.empty([5,2,4])
U[:,0,:] = x * 2
U[:,1,:] = x * 4

but I wish to do this automatically (in particular without for loops). Ideally with a one line command like

U[:,?,:] = x * ?

Is there something to substitute to ? to make it work? It is important to avoid both to insert the objects manually and the for loops. This because this is a toy model of something much bigger. With huge numbers for loops take too much time.

Thanks.

4
  • np.dstack([x * 2, x * 4]).swapaxes(1,2), with a lot of guessing about the invariants of the problem. Commented Aug 26, 2022 at 9:19
  • Anyhow, this solution implies to list all the arrays manually, which is what I want to avoid (this is a toy example for a wider problem with arrays of huge dimension) Commented Aug 26, 2022 at 9:31
  • 1
    Don't assume that anyone who commented also voted, up or down. My guess is that downvoters in particular, don't comment and don't revisit the question. They've expressed their opinion, and moved on to more interesting questions. Complaints are useless. Commented Aug 26, 2022 at 17:34
  • @hpaulj: I totally agree. I didn't mean that, I just wrote "thanks" and the rest in the same message because I'm used to occupying as least space as possible. Commented Aug 26, 2022 at 21:30

1 Answer 1

1

In numpy 'iteration without loops' means using compiled numpy methods to iterate in c code. It just moves the loops to a more efficient level.

In [2]: x = np.ones([5,4],int)

Your example:

In [3]: U = np.empty([5,2,4])
   ...: U[:,0,:] = x * 2
   ...: U[:,1,:] = x * 4

In [4]: U
Out[4]: 
array([[[2., 2., 2., 2.],
        [4., 4., 4., 4.]],

       [[2., 2., 2., 2.],
        [4., 4., 4., 4.]],

       [[2., 2., 2., 2.],
        [4., 4., 4., 4.]],

       [[2., 2., 2., 2.],
        [4., 4., 4., 4.]],

       [[2., 2., 2., 2.],
        [4., 4., 4., 4.]]])

Doing the same thing with a simple broadcasted elementwise multiplication. With the None I'm creating (5,1,4) and (2,1) arrays, which broadcast to (5,2,4).

In [5]: x[:,None,:]*np.array([2,4])[:,None]
Out[5]: 
array([[[2, 2, 2, 2],
        [4, 4, 4, 4]],

       [[2, 2, 2, 2],
        [4, 4, 4, 4]],

       [[2, 2, 2, 2],
        [4, 4, 4, 4]],

       [[2, 2, 2, 2],
        [4, 4, 4, 4]],

       [[2, 2, 2, 2],
        [4, 4, 4, 4]]])

Basically this requires understanding numpy basics, especially how the operators work with broadcasting.

A variant on @Michael's dstack:

In [7]: np.stack([x*2, x*4], axis=1).shape
Out[7]: (5, 2, 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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.