I want to create a MATLAB-like cell array in Numpy. How can I accomplish this?
1 Answer
Matlab cell arrays are most similar to Python lists, since they can hold any object - but scipy.io.loadmat imports them as numpy object arrays - which is an array with dtype=object.
To be honest though you are just as well off using Python lists - if you are holding general objects you will loose almost all of the advantages of numpy arrays (which are designed to hold a sequence of values which each take the same amount of memory).
2 Comments
levesque
The one thing that I am missing by using python lists is the possibility of indexing the array with an array of indexes. Thanks for making me discover numpy object arrays :)
Haymo Kutschbach
Possibly the biggest drawback with the 'array of object' approach is that Matlab cells have value semantics: storing an array A into a cell C protects the cell element from changes to A afterwards. Where ndarray with dtype=object will simply store a reference to A, Matlab stores a lazy, copy-on-write clone. This difference exists throughout numpy, though. You'll find it when using arrays as function parameters, f.e.