Pete
Pete

Reputation: 784

Matlab cell2mat function in Python Numpy?

Does numpy have the cell2mat function? Here is the link to matlab. I found an implementation of something similar but it only works when we can split it evenly. Here is the link.

Upvotes: 0

Views: 3500

Answers (2)

hpaulj
hpaulj

Reputation: 231385

In a sense Python has had 'cells' at lot longer than MATLAB - list. a python list is a direct substitute for a 1d cell (or rather, cell with size 1 dimension). A 2d cell could be represented as a nested list. numpy arrays with dtype object also work. I believe that is what scipy.io.loadmat uses to render cells in .mat files.

np.array() converts a list, or lists of lists, etc, to a ndarray. Sometimes it needs help specifying the dtype. It also tries to render the input to as high a dimensional array as possible.

np.array([1,2,3])
np.array(['1',2,'abc'],dtype=object)
np.array([[1,2,3],[1,2],[3]])
np.array([[1,2],[3,4]])

And MATLAB structures map onto Python dictionaries or objects.

http://docs.scipy.org/doc/scipy/reference/generated/scipy.io.loadmat.html

loadmat can also represent structures as numpy structured (record) arrays.

There is np.concatenate that takes a list of arrays, and its convenience derivatives vstack, hstack, dstack. Mostly they tweak the dimensions of the arrays, and then concatenate on one axis.


Here's a rough approximation to the MATLAB cell2mat example:

C = {[1],    [2 3 4];
     [5; 9], [6 7 8; 10 11 12]}

construct ndarrays with same shapes

In [61]: c11=np.array([[1]])    
In [62]: c12=np.array([[2,3,4]])
In [63]: c21=np.array([[5],[9]])
In [64]: c22=np.array([[6,7,8],[10,11,12]]) 

Join them with a combination of hstack and vstack - i.e. concatenate along the matching axes.

In [65]: A=np.vstack([np.hstack([c11,c12]),np.hstack([c21,c22])])
# or A=np.hstack([np.vstack([c11,c21]),np.vstack([c12,c22])])

producing:

array([[ 1,  2,  3,  4],
       [ 5,  6,  7,  8],
       [ 9, 10, 11, 12]])

Or more generally (and compactly)

In [75]: C=[[c11,c12],[c21,c22]]
In [76]: np.vstack([np.hstack(c) for c in C])

Upvotes: 2

farenorth
farenorth

Reputation: 10781

I usually use object arrays as a replacement for Matlab's cell arrays. For example:

cell_array = np.array([[np.arange(10)],
                       [np.arange(30,40)] ],
                       dtype='object')

Is a 2x1 object array containing length 10 numpy array vectors. I can perform the cell2mat functionality by:

arr = np.concatenate(cell_array).astype('int')

This returns a 2x10 int array. You can change .astype('int') to be whatever data type you need, or you could grab it from one of the objects in your cell_array,

arr = np.concatenate(cell_array).astype(cell_array[0].dtype)

Good luck!

Upvotes: 1

Related Questions