将Matlab矩阵读入Python

时间:2013-02-07 03:16:26

标签: python matlab python-2.7 scipy

当我试图将一个Matlab矩阵读入python时,我收到以下错误

>>> scipy.io.loadmat("Dynamical.mat")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/dist-packages/scipy/io/matlab/mio.py", line 151, in loadmat
    MR = mat_reader_factory(file_name, appendmat, **kwargs)
  File "/usr/lib/python2.7/dist-packages/scipy/io/matlab/mio.py", line 105, in mat_reader_factory
    mjv, mnv = get_matfile_version(byte_stream)
  File "/usr/lib/python2.7/dist-packages/scipy/io/matlab/miobase.py", line 221, in get_matfile_version
    % ret)
ValueError: Unknown mat file type, version 46, 48

Dynamical.mat是一个包含矩阵

的文件
% Size = 30 30 
% Nonzeros = 252 
zzz = zeros(252,3);
zzz = [
1 1  1.4019896354966477e+01
1 2  0.0000000000000000e+00
1 3  0.0000000000000000e+00
...

1 个答案:

答案 0 :(得分:2)

此问题似乎暂时无效,但如果您仍然需要阅读此.mat文件,假设它始终采用您指定的格式,则最好放一个替代方案:

def read_mat( file_path ):
    import numpy as np
    mat = open(file_path, 'r')
    mat.next() # % Size = 30 30
    length = int(mat.next().split()[-1])
    mat.next() # zzz = zeros(18,3)
    mat.next() # zzz = [
    ans = np.array([ map(float, mat.next().split()) for i in xrange(length) ])
    mat.close()
    return ans