3

I am trying to vectorize the following loop in I am trying to append multiple arrays to an empty array.

# ff is a matrix of shape [100,1,96]
temp = np.array([]).reshape(0,96)
for kk in range(1,10,1):
   temp = np.append(tr,ff[kk],axis=0)
temp = temp.reshape(1,10,96)

Is it possible to vectorize the above loop using numpy? Any help is welcome!

5
  • can you explain what you are trying to do? Commented Jan 26, 2017 at 23:24
  • I am trying to loop over elements of a matrix of dimension [100,1,96] which are of dimension [1,96] and appending to them to create [10,96] array Commented Jan 26, 2017 at 23:26
  • So the first 10 entries of the first dimension and all entries of all other dimensions? Shouldn't ff[:10,:,:] just give you the data you are looking for? Commented Jan 26, 2017 at 23:28
  • yes, that works perfectly. Thank you very much! Commented Jan 26, 2017 at 23:33
  • Regarding array append v. list append: stackoverflow.com/a/41793600/901925 Commented Jan 27, 2017 at 1:00

1 Answer 1

2

You can use slicing to extract the data you need:

ff[:10,:,:]

That will yield an array of shape (10, 1, 96). To get rid of the empty dimension, you can run it through numpy.squeeze():

numpy.squeeze(ff[:10,:,:])

and get an array of shape (10, 96)

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.