15

I want to create a MATLAB-like cell array in Numpy. How can I accomplish this?

1 Answer 1

18

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).

Sign up to request clarification or add additional context in comments.

2 Comments

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 :)
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.

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.