1

I am trying to run from Python a script in Matlab that run a Simulink mode, save a variable as Power.mat and read this variable in Python. I am using Python 2.7 on Windows.

I've tried to use the library hdf5storage to read the file:

import hdf5storage
x=hdf5storage.loadmat('Power.mat','r')

but I get the error attached. error

Which could be the problem? I have also tried with the library h5py but I get the same error. The file .mat seems not to be corrupted since I open it without any problem in Matlab.

Thanks!

Jean-François Fabre
  • 126,787
  • 22
  • 103
  • 165
  • Is this relevant? http://stackoverflow.com/questions/31287744/corrupt-files-when-creating-hdf5-files-without-closing-them-h5py – cdarke Oct 13 '16 at 08:00
  • `x=hdf5storage.loadmat('Power.mat')` should work, although it takes forever to download the packages necessary to test it :) – Jean-François Fabre Oct 13 '16 at 08:12
  • 1
    Did you save `Power.mat` as a version 7.3 MAT file? Previous versions are not HDF5. From MATLAB: `type('Power.mat')` will tell you the MAT file version. Use `save('Power.mat', '-v7.3')` to specify the version. – smn Oct 13 '16 at 08:22
  • Possible duplicate of [Read .mat files in Python](http://stackoverflow.com/questions/874461/read-mat-files-in-python) – obchardon Oct 13 '16 at 14:53

2 Answers2

3

You can use scipy.io to exchange data between Python and Matlab. There are functions named savemat and loadmat for this purpose.

Something like this should work:

import scipy.io
mat = scipy.io.loadmat('Power.mat')

For reference, http://docs.scipy.org/doc/scipy/reference/generated/scipy.io.loadmat.html

minhduc
  • 163
  • 2
  • 11
  • 3
    There are four different `.mat` file formats. The first three, `v4`, `v6`, and `v7`, are proprietary binary formats. Those are what `scipy` can open. The last, `v7.3`, is a specialized hdf5 file. That is what `hdf5storage` can open. Technically it can be opened by anything that can handle hdf5 files, but hdf5storage has some tools to gracefully handle the MATLAB-specific bits. Otherwise you get a pretty ugly (but still ultimately usable) output. – TheBlackCat Oct 13 '16 at 12:53
0

Try this code :

import h5py
Data = h5py.File('File.mat')
Fabich
  • 2,080
  • 2
  • 25
  • 32
RVK
  • 305
  • 1
  • 3
  • 12
  • 1
    This is useless, it just gives me a bunch of hd5 reference objects. I can't do anything with them – raaj Mar 11 '18 at 05:39