The loadmat() function enables importing data from a MATLAB file.
It takes one required parameter:
filename: The name of the file containing the saved data.
It returns a structured array where the keys are the variable names and the values are the corresponding variable values.
Import the array from the following MAT file.
from scipy import io import numpy as np arr = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9,]) # Export: io.savemat(‘arr.mat’, {“vec”: arr}) # Import: mydata = io.loadmat(‘arr.mat’) print(mydata) |
{ ‘__header__’: b’MATLAB 5.0 MAT-file Platform: nt, Created on: Tue Sep 22 13:12:32 2020′, ‘__version__’: ‘1.0’, ‘__globals__’: [], ‘vec’: array([[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]]) } |
Use the variable name “vec” to display only the array from the MATLAB data.
… print(mydata[‘vec’]) |
[[0 1 2 3 4 5 6 7 8 9]] |
Note: We can observe that the array was originally 1D, but after extraction, it has gained an additional dimension.
To resolve this, we can pass an extra argument squeeze_me=True
.
# Import: mydata = io.loadmat(‘arr.mat’, squeeze_me=True) print(mydata[‘vec’]) |
[0 1 2 3 4 5 6 7 8 9] |