让Python和Matlab协同工作 (1)

**如何从Python中导出".mat"文件**
很多时候,需要将Python之中处理过的数据导出为.mat文件中的矩阵,供Matlab使用。这个时候可以使用scipy的sio模块,这个模块的全称是:File IO ([scipy.io](http://docs.scipy.org/doc/scipy/reference/io.html#module-scipy.io))。

目前支持这些类型的文件的读写

  • Matlab files(*.mat)
  • Matrix Market files(*.mtx)
  • WAV files(*.wav)
  • Arff files, arff is a simple file format which support numerical, string and data values. It supports sparse data too, see http://weka.sourceforge.net/wekadoc/index.php/en:ARFF_(3.4.6) for more info. scipy.io对这个模块只支持读
  • NetCDF这里呼应标题,只讲如何存数据到Matlab中的数组,给一个例子吧
    01 # -*-   encoding : utf8   -*-
    02 import os
    03 import scipy.io as sio
    04 from wfdbtools import rdsamp, rdann
    05 
    06 # 为了处理命令行选项
    07 from optparse import OptionParser
    08 # 命令行选项
    09 parser  = OptionParser(version="%prog 0.1",\
    10                        usage="python %prog [options]")
    11 
    12 parser.add_option("-i", "--in", action="store", \
    13         dest="IN", \
    14         default="All/106", \
    15         help="whether output binary frames into file.")
    16 
    17 parser.add_option("-s", "--start", action="store",\
    18         type="int", dest="START",\
    19         default="0", \
    20         help="start time [default=0]")
    21 
    22 parser.add_option("-e", "--end", action="store",\
    23         type="int", dest="END",\
    24         default="-1",\
    25         help="end time [default=-1]")
    26 
    27 parser.add_option("-o", "--out", action="store",\
    28         type="string", dest="OUT",\
    29         default="Data.mat",\
    30         help="output file name [default=Data.mat]")
    31 
    32 (options, args) = parser.parse_args()
    33 
    34 def main():
    35     '''
    36         idiot comment
    37     '''
    38     # read data from sample files
    39     data, info = rdsamp(options.IN, options.START, options.END)
    40     ann = rdann(options.IN, 'atr', options.START, options.END)
    41     start   = int(data[0,0])
    42     p       = 0
    43     # list of NOR points
    44     ln  = list()
    45     # list of PVC points
    46     lp  = list()
    47     for d in ann:
    48         p = int(d[0]) - start
    49         if int(d[2]) == 5:
    50             lp.append(data[p-36:p+55, 2])
    51         elif int(d[2]) == 1:
    52             ln.append(data[p-36:p+55, 2]) 
    53     # write data to mat file
    54     l_dic   = dict()
    55     for i in range(len(lp)):
    56         l_dic["PVC"+str(i)] = lp[i]
    57     for i in range(len(ln)):
    58         l_dic["NOR"+str(i)] = ln[i]
    59     # write ann
    60     sio.savemat("ANN_" + options.OUT, {'ANN':ann}, oned_as='column')
    61     sio.savemat(options.OUT, l_dic, oned_as='row')
    62 
    63 if __name__ == "__main__":
    64     main() 
    这个例子是从MIT-BIT数据库中把数据倒出为mat文件中的数组的,其实只要关注带有sio.savemat函数的那两行(6061两行),这个函数的用途在于可以吧Python中的dict数据存入到mat文件中。

它的第一个参数是输出的mat文件的文件名(带扩展名),第二个参数是将要被存储的dict数据,第三个参数有两个可选的选项”row”和”column”,也就是对一维的数据(比如list)是为mat文件中的1N矩阵还是N1矩阵。

如何在Python中读入”.mat”文件

如上文所说,这个时候你也需要scipy.io,不同的是,调用loadmat函数而已。详细使用方法请参见: scipy.io.loadmat