13

I am trying to export a list of text strings from Python to MATLAB using scipy.io. I would like to use scipy.io because my desired .mat file should include both numerical matrices (which I learned to do here) and text cell arrays.

I tried:

import scipy.io
my_list = ['abc', 'def', 'ghi']
scipy.io.savemat('test.mat', mdict={'my_list': my_list})

In MATLAB, I load test.mat and get a character array:

my_list =

adg
beh
cfi

How do I make scipy.io export a list into a MATLAB cell array?

Community
  • 1
  • 1
wwwilliam
  • 9,142
  • 8
  • 30
  • 33
  • 2
    You might also be interested in my python-in-MATLAB project: http://github.com/kw/pymex – kenm Mar 12 '10 at 16:44

2 Answers2

13

You need to make my_list an array of numpy objects:

import scipy.io
import numpy as np
my_list = np.zeros((3,), dtype=np.object)
my_list[:] = ['abc', 'def', 'ghi']
scipy.io.savemat('test.mat', mdict={'my_list': my_list})

Then it will be saved in a cell format. There might be a better way of putting it into a np.object, but I took this way from the Scipy documentation.

Justin Peel
  • 46,722
  • 6
  • 58
  • 80
  • For posterity: an easier way to make an object array is `np.asarray(['abc', 'def', 'ghi'], dtype='object')`. – Danica May 27 '14 at 23:19
1

It looks like the contents of the list are exported properly, they are just transposed and placed in a character array. You can easily convert it to the desired cell array of strings in MATLAB by transposing it and using CELLSTR, which places each row in a separate cell:

>> my_list = ['adg';'beh';'cfi'];  %# Your example
>> my_list = cellstr(my_list')    %'# A 3-by-1 cell array of strings

my_list = 

    'abc'
    'def'
    'ghi'

Granted, this doesn't address the more general issue of exporting data as a cell array from Python to MATLAB, but it should help with the specific problem you list above.

gnovice
  • 125,304
  • 15
  • 256
  • 359