Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create empty 3D numpy array and append it with each new given value

I feel like there has to be an easy solution to this, but I'm not too familiar with Numpy yet and couldn't find anything in the library fitting my needs. I feel like this is an obvious thing, but I couldn't find any similar question regarding this on StackOverflow.

Basically, I want to create a 3-dimensional empty array. I tried it like this: matrix = np.array(None, ndmin=3). And now every time I have a new variable I want to append a dimension of the matrix I chose with the new value of the variable. How can I do that? I played around with np.append() and np.insert() but I couldn't come to a solution.

like image 676
hlzl Avatar asked Oct 20 '25 15:10

hlzl


1 Answers

Arrays have a fixed size. You can't append to them. If you know the upper bounds of the array, you can preallocate the array with

np.empty((10, 10, 10))

For a 10x10x10 matrix. You can then keep 3 indices x,y,z to track the actual size you have. Eg, add a new element with:

matrix[x,y,z] = newElement
x += 1

Then when you're done, you can extract the submatrix with

finalMatrix = matrix[:x,:y,:z]
like image 60
Oren Bell Avatar answered Oct 23 '25 05:10

Oren Bell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!