Skip to content Skip to sidebar Skip to footer

Errors Create When Loading Matlab Files Into Python

I am having some trouble loading a .mat file into Python. It is a structured array with many main and subheadings etc. and I have two errors when using two different modules to imp

Solution 1:

If it is saved with the -v7.3 flag you can use the h5py library. Edited to show how to walk through a matfile with structs, cells, arrays etc.

import h5py
from numpy import ndarray

def explore_v73_matfile(file_name=None, fptr=None, path=None):
    if file_name is not None:
        # open the file
        fptr = h5py.File(file_name)
        explore_v73_matfile(None, fptr, ["/"])
        return
    # walk the file tree. not super efficient if very nested, BUT
    # it is very difficult to address if there is a mix of char and
    # int subscripts (nested cells/structs etc)
    o = fptr[path[0]]
    for p in path[1:]:
        o = o[p]
    if isinstance(o, (h5py._hl.group.Group, h5py._hl.files.File)):
        for k in o.keys():
            if (k == "#refs#"):
                # nothing we need is stored under this key
                continue
            else:
                explore_v73_matfile(None, fptr, path + [k])
    elif isinstance(o, h5py._hl.dataset.Dataset):
        if (o.dtype == "|O"):
            # should work for 1D, 2D, ... ND
            for cell in range(o.shape[0]):
                # MATLAB cell array
                explore_v73_matfile(None, fptr, path + [cell])
        else:
            # probably numeric, maybe char (check dtype)
            # this is where you'd find your numeric data arrays 
            print("/".join(map(str,path[1:])))
            print(o[:])
    elif isinstance(o, ndarray):
        # we're walking through a cell or struct array
        for cell in range(len(o)):
            explore_v73_matfile(None, fptr, path + [cell])
    elif isinstance(o, h5py.h5r.Reference):
        # sometimes structs get linked elsewhere if you stuff them in cells

        # print here because the full address gets replaced by [o]
        print("/".join(map(str,path[1:])))
        explore_v73_matfile(None, fptr, [o])
    else:
        raise TypeError("Undefined Behavior. Check MAT File")

Post a Comment for "Errors Create When Loading Matlab Files Into Python"