I am a Matlab user new to Python. I would like to write a cell array of strings in Matlab to a Mat file, and load this Mat file using Python (maybe scipy.io.loadmat) into some similar type (e.g list of strings or tuple of strings). But loadmat read things into array and I am not sure how to convert it into a list. I tried the "tolist" function which does not work as I expected ( I have a poor understanding of Python array or numpy array). For example:
Matlab code:
cell_of_strings = {'thank', 'you', 'very', 'much'};
save('my.mat', 'cell_of_strings');
Python code:
matdata=loadmat('my.mat', chars_as_strings=1, matlab_compatible=1);
array_of_strings = matdata['cell_of_strings']
Then, the variable array_of_strings is:
array([[[[u't' u'h' u'a' u'n' u'k']], [[u'y' u'o' u'u']],
[[u'v' u'e' u'r' u'y']], [[u'm' u'u' u'c' u'h']]]], dtype=object)
I am not sure how to convert this array_of_strings into a Python list or tuple so that it looks like
list_of_strings = ['thank', 'you', 'very', 'much'];
I am not familiar with the array object in Python or numpy. Your help will be highly appreciated.
Have your tried this:
import scipy.io as si
a = si.loadmat('my.mat')
b = a['cell_of_strings'] # type(b) <type 'numpy.ndarray'>
list_of_strings = b.tolist() # type(list_of_strings ) <type 'list'>
print list_of_strings
# output: [u'thank', u'you', u'very', u'much']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With