creating a .mat file from python

vipints picture vipints · Oct 6, 2009 · Viewed 32.8k times · Source

I have a variable exon = [[[1, 2], [3, 4], [5, 6]], [[7, 8], [9, 10]]]. I would like to create a mat file like the following

>>

exon : [3*2 double] [2*2 double]

When I used the python code to do the same it is showing error message. here is my python code

import scipy.io
exon  = [[[1, 2], [3, 4], [5, 6]], [[7, 8], [9, 10]]]
scipy.io.savemat('/tmp/out.mat', mdict={'exon': (exon[0], exon[1])})

It will be great anyone can give a suggestion for the same. thanks in advance Vipin T S

Answer

robince picture robince · Oct 29, 2009

You seem to want two different arrays linked to same variable name in Matlab. That is not possible. In MATLAB you can have cell arrays, or structs, which contain other arrays, but you cannot have just a tuple of arrays assigned to a single variable (which is what you have in mdict={'exon': (exon[0], exon1)) - there is no concept of a tuple in Matlab.

You will also need to make your objects numpy arrays:

import numpy as np
exon = [ np.array([[1, 2], [3, 4], [5, 6]]), np.array([[7, 8], [9, 10]]) ]

There is scipy documentation here with details of how to save different Matlab types, but assuming you want cell array:

obj_arr = np.zeros((2,), dtype=np.object)
obj_arr[0] = exon[0]
obj_arr[1] = exon[1]
scipy.io.savemat('/tmp/out.mat', mdict={'exon': obj_arr})

this will result in the following at matlab:

code result in matlab

or possibly (untested):

obj_arr = np.array(exon, dtype=np.object)