views:

319

answers:

2

Right, perhaps I should be using the normal Python lists for this, but here goes:

I want a 9 by 4 multidimensional array/matrix (whatever really) that I want to store arrays in. These arrays will be 1-dimensional and of length 4096.

So, I want to be able to go something like

column = 0                                    #column to insert into
row = 7                                       #row to insert into
storageMatrix[column,row][0] = NEW_VALUE
storageMatrix[column,row][4092] = NEW_VALUE_2
etc..

I appreciate I could be doing something a bit silly/unnecessary here, but it will make it ALOT easier for me to have it structured like this in my code (as there's alot of these, and alot of analysis to be done later).

Thanks!

A: 

The Tentative NumPy Tutorial says you can declare a 2D array using the comma operator:

x = ones( (3,4) )

and index into a 2D array like this:

>>> x[1,2] = 20
>>> x[1,:]                             # x's second row
array([ 1,  1, 20,  1])
>>> x[0] = a                           # change first row of x
>>> x
array([[10, 20, -7, -3],
       [ 1,  1, 20,  1],
       [ 1,  1,  1,  1]])
David
Ok you've got the right idea in the first part: I might not have explained myself properly. So setting up the ones((3,4)) is right... now imagine for each of those 1's in the array I want there to be an array (for arguments sake, [1,2,3])... how would I do that?
Duncan Tait
I suppose I could make a 3-dimensional array actually, that's pretty confusing though.
Duncan Tait
No cos now I need a 4-d one and thats a shame cos the 4th dimension affects the other 3, and I only want it to affect the 3rd dimension :(
Duncan Tait
+3  A: 

Note that to leverage the full power of numpy, you'd be much better off with a 3-dimensional numpy array. Breaking apart the 3-d array into a 2-d array with 1-d values may complicate your code and force you to use loops instead of built-in numpy functions.

It may be worth investing the time to refactor your code to use the superior 3-d numpy arrays.

However, if that's not an option, then:

import numpy as np
storageMatrix=np.empty((4,9),dtype='object')

By setting the dtype to 'object', we are telling numpy to allow each element of storageMatrix to be an arbitrary Python object.

Now you must initialize each element of the numpy array to be an 1-d numpy array:

storageMatrix[column,row]=np.arange(4096)

And then you can access the array elements like this:

storageMatrix[column,row][0] = 1
storageMatrix[column,row][4092] = 2
unutbu
Awesome, that's perfect - and in actual fact I will refactor my code to use 3D arrays, it makes sense.
Duncan Tait