Hướng dẫn loadmat python

There is a nice package called mat4py which can easily be installed using

pip install mat4py

It is straightforward to use (from the website):

Load data from a MAT-file

The function loadmat loads all variables stored in the MAT-file into a simple Python data structure, using only Python’s dict and list objects. Numeric and cell arrays are converted to row-ordered nested lists. Arrays are squeezed to eliminate arrays with only one element. The resulting data structure is composed of simple types that are compatible with the JSON format.

Example: Load a MAT-file into a Python data structure:

from mat4py import loadmat

data = loadmat('datafile.mat')

The variable data is a dict with the variables and values contained in the MAT-file.

Save a Python data structure to a MAT-file

Python data can be saved to a MAT-file, with the function savemat. Data has to be structured in the same way as for loadmat, i.e. it should be composed of simple data types, like dict, list, str, int, and float.

Example: Save a Python data structure to a MAT-file:

from mat4py import savemat

savemat('datafile.mat', data)

The parameter data shall be a dict with the variables.

scipy.io.loadmat(file_name, mdict=None, appendmat=True, **kwargs)[source]#

Load MATLAB file.

Parametersfile_namestr

Name of the mat file (do not need .mat extension if appendmat==True). Can also pass open file-like object.

mdictdict, optional

Dictionary in which to insert matfile variables.

appendmatbool, optional

True to append the .mat extension to the end of the given filename, if not already present. Default is True.

byte_orderstr or None, optional

None by default, implying byte order guessed from mat file. Otherwise can be one of (‘native’, ‘=’, ‘little’, ‘<’, ‘BIG’, ‘>’).

mat_dtypebool, optional

If True, return arrays in same dtype as would be loaded into MATLAB (instead of the dtype with which they are saved).

squeeze_mebool, optional

Whether to squeeze unit matrix dimensions or not.

chars_as_stringsbool, optional

Whether to convert char arrays to string arrays.

matlab_compatiblebool, optional

Returns matrices as would be loaded by MATLAB (implies squeeze_me=False, chars_as_strings=False, mat_dtype=True, struct_as_record=True).

struct_as_recordbool, optional

Whether to load MATLAB structs as NumPy record arrays, or as old-style NumPy arrays with dtype=object. Setting this flag to False replicates the behavior of scipy version 0.7.x (returning NumPy object arrays). The default setting is True, because it allows easier round-trip load and save of MATLAB files.

verify_compressed_data_integritybool, optional

Whether the length of compressed sequences in the MATLAB file should be checked, to ensure that they are not longer than we expect. It is advisable to enable this (the default) because overlong compressed sequences in MATLAB files generally indicate that the files have experienced some sort of corruption.

variable_namesNone or sequence

If None (the default) - read all variables in file. Otherwise, variable_names should be a sequence of strings, giving names of the MATLAB variables to read from the file. The reader will skip any variable with a name not in this sequence, possibly saving some read processing.

simplify_cellsFalse, optional

If True, return a simplified dict structure (which is useful if the mat file contains cell arrays). Note that this only affects the structure of the result and not its contents (which is identical for both output structures). If True, this automatically sets struct_as_record to False and squeeze_me to True, which is required to simplify cells.

Returnsmat_dictdict

dictionary with variable names as keys, and loaded matrices as values.

Notes

v4 (Level 1.0), v6 and v7 to 7.2 matfiles are supported.

You will need an HDF5 Python library to read MATLAB 7.3 format mat files. Because SciPy does not supply one, we do not implement the HDF5 / 7.3 interface here.

Examples

>>> from os.path import dirname, join as pjoin
>>> import scipy.io as sio

Get the filename for an example .mat file from the tests/data directory.

>>> data_dir = pjoin(dirname(sio.__file__), 'matlab', 'tests', 'data')
>>> mat_fname = pjoin(data_dir, 'testdouble_7.4_GLNX86.mat')

Load the .mat file contents.

>>> mat_contents = sio.loadmat(mat_fname)

The result is a dictionary, one key/value pair for each variable:

>>> sorted(mat_contents.keys())
['__globals__', '__header__', '__version__', 'testdouble']
>>> mat_contents['testdouble']
array([[0.        , 0.78539816, 1.57079633, 2.35619449, 3.14159265,
        3.92699082, 4.71238898, 5.49778714, 6.28318531]])

By default SciPy reads MATLAB structs as structured NumPy arrays where the dtype fields are of type object and the names correspond to the MATLAB struct field names. This can be disabled by setting the optional argument struct_as_record=False.

Get the filename for an example .mat file that contains a MATLAB struct called teststruct and load the contents.

>>> matstruct_fname = pjoin(data_dir, 'teststruct_7.4_GLNX86.mat')
>>> matstruct_contents = sio.loadmat(matstruct_fname)
>>> teststruct = matstruct_contents['teststruct']
>>> teststruct.dtype
dtype([('stringfield', 'O'), ('doublefield', 'O'), ('complexfield', 'O')])

The size of the structured array is the size of the MATLAB struct, not the number of elements in any particular field. The shape defaults to 2-D unless the optional argument squeeze_me=True, in which case all length 1 dimensions are removed.

>>> teststruct.size
1
>>> teststruct.shape
(1, 1)

Get the ‘stringfield’ of the first element in the MATLAB struct.

>>> teststruct[0, 0]['stringfield']
array(['Rats live on no evil star.'],
  dtype='

Get the first element of the ‘doublefield’.

>>> teststruct['doublefield'][0, 0]
array([[ 1.41421356,  2.71828183,  3.14159265]])

Load the MATLAB struct, squeezing out length 1 dimensions, and get the item from the ‘complexfield’.

>>> matstruct_squeezed = sio.loadmat(matstruct_fname, squeeze_me=True)
>>> matstruct_squeezed['teststruct'].shape
()
>>> matstruct_squeezed['teststruct']['complexfield'].shape
()
>>> matstruct_squeezed['teststruct']['complexfield'].item()
array([ 1.41421356+1.41421356j,  2.71828183+2.71828183j,
    3.14159265+3.14159265j])

Can Python import .MAT files?

Matlab 7.3 and greater Beginning at release 7.3 of Matlab, mat files are actually saved using the HDF5 format by default (except if you use the -vX flag at save time, see in Matlab). These files can be read in Python using, for instance, the PyTables or h5py package.

How do I run a .MAT file in Python?

By default, Python is not capable of reading . mat files. We need to import a library that knows how to handle the file format..

Install scipy. Similar to how we use the CSV module to work with . ... .

Import the scipy. io. ... .

Parse the . ... .

Use Pandas dataframes to work with the data..

How do I open a .MAT file?

How to Open an MAT File. MAT files that are Microsoft Access Shortcut files can be created by dragging a table out of Access and to the desktop or into another folder. Microsoft Access needs to be installed in order to use them. MATLAB from MathWorks can open MAT files that are used by that program.

How do I load a .MAT file in Colab?

1 Answer.

upload your . mat file on your drive..

add these lines at the top of your code from google.colab import drive drive.mount('/content/drive').

then just load using the following path S=scipy.io.loadmat('/content/drive/My Drive/burgers_shock.mat');.