# How to convert Matlab Cell Array into Python Numpy Array?

191 views (last 30 days)
Rachel Dawn on 7 Nov 2022
Edited: Suvansh Arora on 10 Nov 2022
In matlab, I generate a random number of images, each of the shape (130,100). In this case, the number of images generated was 9. I save them into a cell array like below.
Then, I'd like to import this cell array into python numpy array of the shape (9,130,100). I've tried the following but I get this value error below.
import scipy.io as sio
import numpy
num_imgs=len(imgs['img_array'][0])
img_array=np.array(imgs['img_array'][0])
new_array=img_array.reshape((num_imgs,130,100))
ValueError: cannot reshape array of size 9 into shape (9,130,100)
If there's a more efficient way to save these images in matlab (for later converting to numpy arrays), I can do it that way too.

Suvansh Arora on 10 Nov 2022
Edited: Suvansh Arora on 10 Nov 2022
One of the possible ways is to convert the “cell array” to “double array” and then convert the “double array” to “NumPy array”.
There are couple of ways to convert “double arrays” to “NumPy array”, One method is to use the “NumPy'sbuilt-in method, “asarray:
• With MATLAB R2022a and later, you can convert MATLAB Double directly to a NumPy array:
a = np.array(myData['cluster_class'])
• To add additional specification, use MATLAB engine's functions to convert to a Python array with noncomplex(), then to a NumPy array:
a = np.array(myData['cluster_class'].noncomplex().toarray(), 'int')
We use the noncomplex() call to retrieve the data in 1D format (provided it's noncomplex; for complex data, we can use “real() and imag() calls). We also offer the toarray() call to convert a 1D MATLAB “double” into a Python array.array” object.