2

Perhaps a simple questions, but I am using numpy, and iteratively generating 9x9x9 matrices.

I would like to stack these so I end up with Nx9x9x9, but using append, stack and stack it seems to vectorise one of the dimensions rather than add these as individual objects. any ideas how I can do this?

thanks

1 Answer 1

2

This could be resolved using np.vstack but to get this in the shape you want to need to add another dimension (an empty one) as first. Otherwise you would stack you current first dimension:

import numpy as np
a = np.ones((1,2,2,2))
print(a.shape) # (1, 2, 2, 2)

or if you create your arrays, then add another dimension by:

a = np.ones((2,2,2))
a = a[None, :]  # Adds an dimension as first

and then to stack them you could use:

b = np.vstack([a,a])
print(b.shape) # (2, 2, 2, 2)
c = np.vstack([b,a])
print(c.shape) # (3, 2, 2, 2)
c.shape

you said you create them iterativly but if you only need the final result at the end you don't even need to use vstack just create a new array:

a = np.ones((9,9,9))
b = np.ones((9,9,9))
c = np.ones((9,9,9))
d = np.ones((9,9,9))
res = np.array([a, b, c, d])
print(res.shape) # (4, 9, 9, 9)
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks so much :) I didn't know how to add an extra dimension to my 3 dimensional matrix! Very helpful
@i-am-spartacus You're welcome! If this really solves your problem it would be nice if you upvote or accept the answer. :)
np.array([a,b,c,d]) should produce the same thing. np.vstack([i[None,...] for i in [a,b,c,d]]) is another expression.
@hpaulj - Yes, at first I thought of it and then forgot about it because he mentioned creating them iteratively and I wasn't quite certain what he meant. Thanks for the comment, I'll edit it.

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.