Last active
July 19, 2022 18:34
-
-
Save esmitt/4c58b12eddb10dd657886a8e78c8fca9 to your computer and use it in GitHub Desktop.
A simple function to load a .mat file using scipy from Python. It uses a recursive approach for parsing properly Matlab' objects
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import scipy.io as scio | |
from typing import Any, Dict | |
import numpy as np | |
def load_matfile(filename: str) -> Dict: | |
def parse_mat(element: Any): | |
# lists (1D cell arrays usually) or numpy arrays as well | |
if element.__class__ == np.ndarray and element.dtype == np.object_ and len(element.shape) > 0: | |
return [parse_mat(entry) for entry in element] | |
# matlab struct | |
if element.__class__ == scio.matlab.mio5_params.mat_struct: | |
return {fn: parse_mat(getattr(element, fn)) for fn in element._fieldnames} | |
# regular numeric matrix, or a scalar | |
return element | |
mat = scio.loadmat(filename, struct_as_record=False, squeeze_me=True) | |
dict_output = dict() | |
# not considering the '__header__', '__version__', '__globals__' | |
for key, value in mat.items(): | |
if not key.startswith('_'): | |
dict_output[key] = parse_mat(mat[key]) | |
return dict_output | |
if __name__ == "__main__": | |
file = "example.mat" | |
# I am assuming that file exists! otherwise, check for FileNotFoundError | |
dict_mat = load_matfile(file) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment