0

I have a bunch of Matlab structures which have been generated from matlab R2018b version 9.5. The structure contains 3 fields:

  1. A Matrix of double size: 6942x6092
  2. A matrix of double size: 6942x1
  3. A matrix of cell size: 1x6092 (the content of the cells are string)

I would like to find a way to load this structure and access the three different elements in python 3.7. I have tried many ways but I never managed to load the structure and been able to access the 3 elements of the structure. For reproducing the structure in matlab:

struct.values = ones(6942,6092);
struct.dates = ones(6942,1);
struct.id = cell(1,6092);
struct.id(:) = {'x1'};
save('struct','struct');

It is then saved as a .mat file.

Tulkkas
  • 891
  • 3
  • 7
  • 20
  • Are you asking how to load a .mat file in python? See [`h5py`](http://docs.h5py.org/en/stable/), and [this answer](https://stackoverflow.com/a/19340117/3372061). – Dev-iL May 23 '19 at 13:39
  • The answer unfortunately does work in that case. I get the error: "Unable to open file (file signature not found)". I am able to load simple matrices but if you read carefully my question, i am talking about matlab structure. So yes it is a .mat file but containing a structure. – Tulkkas May 23 '19 at 13:54

1 Answers1

0

Dev-iL was basically right, you can load structures with scipy.io.loadmat, not only matrices. See here:

import scipy.io as sio
container = sio.loadmat('struct.mat')
values = container['struct']['values'][0,0]
Yuval Harpaz
  • 1,351
  • 1
  • 11
  • 15
  • If that was not clear, I save my .mat files using v7.3 format. With that in mind, your code above return the following error: "Please use HDF reader for matlab v7.3 files" – Tulkkas May 23 '19 at 14:52
  • did you try the solutions here: https://stackoverflow.com/questions/17316880/reading-v-7-3-mat-file-in-python ? – Yuval Harpaz May 23 '19 at 15:29
  • yes but i get the following error: " Unable to open file (file signature not found)" – Tulkkas May 23 '19 at 15:37
  • I took another look, reading the data with f = h5py.File('struct.mat') did not replicate your error, I don't know why you get it. However, I was only able to get field names, it seems that struct are not supported. Some success was reported by using matlab.engine, which means that you call Matlab with python. This requires Matlab of course. – Yuval Harpaz May 23 '19 at 16:18