8

When I'm trying to read a Matlab matrix into python, I get the following error

>>> 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

The Dynamical.mat is a file containing the matrix

% 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
...
8
  • what version of matlab is this '*.mat' from? Commented Feb 7, 2013 at 4:09
  • 1
    It is output from a Petsc package and has not been generated by Matlab Commented Feb 7, 2013 at 4:52
  • 2
    If Matlab can indeed read these files, a convenience script to start Matlab, and open and re-save the .mat files sounds like it's in order. Commented Feb 7, 2013 at 8:28
  • 1
    also look into h5py. *.mat files are really just hdf files with a very particular layout. Commented Feb 7, 2013 at 14:45
  • 2
    I just find out that Matlab also cant read the file Commented Feb 9, 2013 at 19:22

1 Answer 1

2

This question seems to be inactive for a while, but it is good to let one alternative in case you still need to read this .mat file, assuming it is always in the format you specified:

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
Sign up to request clarification or add additional context in comments.

3 Comments

This won't work because .mat file is not ascii. You will receive the error: could not convert string to float
@ChuNan the answer assumes the format specified by the OP and in this case it works. Do you have an example of a binary .mat file?
I generated a simple 3X3 matrix with all double numbers. When I tried to print mat.next().split(), it shows me :"MATLAB 5.0 MAT-file Platform PCWIN created on......" and then something like x00\x01IM\x0f\x00....

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.