Python Scipy Load Mat File

In this Python tutorial, we will learn about the “Python Scipy Load Mat File” where we will load or read the mat file using the method of Python Scipy and Additionally cover the following topics.

  • Python Scipy Load Mat File
  • Python Scipy Load Mat Struct
  • Python Scipy Load Mat File To Dataframe
  • Python Scipy Load Mat File Hdf5
  • Python Scipy Save And Load Mat File
  • Python Scipy Whosmat File

Also, check the related Scipy tutorial: Python Scipy Differential Evolution

Python Scipy Load Mat File

Before we begin, “What is a mat file?“, The binary data container format used by the MATLAB application is represented by files with the “.mat” extension. The extension was created by Mathworks, and MAT files are classified as data files because they contain variables, arrays, functions, and other kinds of information.

The Python Scipy contains a method loadmat() in a module scipy.io to load the Matlab file.

The syntax is given below.

scipy.io.loadmat(file_name, mdict=None, appendmat=True)

Where parameters are:

  • file_name(str): The file’s name (without the.mat extension if appendmat==True). open file-like objects may also be passed.
  • mdict(dict): Dictionary to input matfile variables.
  • appendmat(boolean): If the ‘.mat extension’ is not already present, add it to the end of the specified filename. True by default.

The method loadmat() returns m_dict which is the dictionary containing loaded matrices as values and variable names as keys.

Let’s see with an example by following the below steps:

Go to website https://matlab.mathworks.com/ and write the below code to save a variable p value to file pqfile.mat in Matlab workspace.

p = rand(1,10);
save('pqfile.mat','p')

After running the above code, it generates a file name pqfile.mat that contains a variables p. Then click on Download the button to download the file on your computer.

Python Scipy Load Mat File Example
Python Scipy Load Mat File Example

Now, we are going to load the file using the method loadmat() using the below code.

from scipy.io import loadmat

loadmat('pqfile.mat')
Python Scipy Load Mat File
Python Scipy Load Mat File

Look at the above output, after loading the file pqfile.mat, it shows the information like header, version, globals and the values of the variable p.

This is how to load the mat file using the method loadmat() of Python Scipy.

READ:  Matplotlib time series plot

Raed: Python Scipy Stats Norm

Python Scipy Load Mat Struct

We know how to use the method loadmat() of Python Scipy to load the mat file, now we will know about the parameter struct_as_record that is accepted by the method loadmat().

struct_as_record(bool): Determining whether to load MATLAB structures as NumPy record arrays or traditional NumPy arrays with dtype=object Setting this value to False duplicates the behavior of scipy version 0.7.x (returning NumPy object arrays) (returning NumPy object arrays). Because it makes round-trip loading and saving of MATLAB files easier, True is the default setting.

Python Scipy Load Mat File To Dataframe

Here in this section, we will load the mat file and convert it into a data frame using the method Dataframe() of Pandas. For instance, we will use the same mat file pqfile.mat that we have created in the above subsection “Python Scipy Load Mat File”.

Let’s import the required libraries or methods using the below python code.

from scipy.io import loadmat
import pandas as pd

Now load the file using the method loadmat() as shown below.

mat = loadmat('pqfile.mat')

The loadmat the method returns the dictionary containing information with variables’ name and their values as key-value pairs.

To access the values of variables in the dictionary. Here we will use the method get() of a dictionary that accepts a key which is a variable name that returns the value associated with the given key, assuming the key is present in the dictionary.

And pass the returned value to the method Dataframe() of Pandas to convert the values to dataframe as shown below.

dataframe = pd.DataFrame(mat.get('p'))

View the converted mat file to the data frame using the below code.

dataframe
Python Scipy Load Mat File To Dataframe
Python Scipy Load Mat File To Dataframe

This is how to load the mat file to dataframe in Python SciPy.

Read: Python Scipy Mann Whitneyu

Python Scipy Load Mat File Hdf5

Here in this section, we will use the package h5py to load the mat file because the method loadmat() can not load the HDF5 of h5 type of file. The HDF5 binary data format has a Pythonic interface called the h5py package.

It enables you to quickly and simply manipulate vast numerical data using NumPy. For instance, multi-terabyte datasets that are kept on the disc can be divided up as if they were actual NumPy arrays. A single file can hold thousands of datasets, each categorized and labeled as desired.

READ:  How to create a function-based view in Django

So here we are going to load the file myrndarray.h5 that we have created using the below code in Matlab.

>> h5create('myrndarray.h5','/DS1',[5 10])
>> myrnddata = rand(5,10);
h5write('myrndarray.h5', '/DS1', myrnddata)
>> h5disp('myrndarray.h5')

Now selects the file and download it on your computer.

Open Jupyter Notebook and install the package h5py using the below python code.

pip install h5py
Python Scipy Load Mat File Hdf5 Example
Python Scipy Load Mat File Hdf5 Example

Import the module h5py using the below code.

import h5py

Read the file myrndarray.h5 that is created by Matlab using the method File() of module h5py.

f_data = h5py.File('myrndarray.h5','r')

Now use the method get() of the dictionary to know about the file info using the below code.

f_data.get('DS1')
Python Scipy Load Mat File Hdf5
Python Scipy Load Mat File Hdf5

The output shows the file format HDF5 with a key equal to DS1 and shapes equally to (10,5). This is how to read the file with the format hdf5 or h5.

Read: Python Scipy Eigenvalues

Python Scipy Save And Load Mat File

So far we have learned how to load the mat file, now in this section, we will know to save and load the mat file. To save the file with .mat extension, we will use the method savemat() of module scipy.io.

The syntax is given below.

scipy.io.savemat(file_name, mdict, appendmat=True, format='5', long_field_names=False, do_compression=False, oned_as='row')

Where parameters are:

  • file_name(str): The file’s name (without the.mat extension if appendmat==True). open file-like objects may also be passed.
  • mdict(dict): Dictionary to input matfile variables.
  • appendmat(boolean): If the ‘.mat extension’ is not already present, add it to the end of the specified filename. True by default.
  • format{4:5}: “5” (the default) for MATLAB versions 5 and higher (up to 7.2), and “4” for MATLAB version 4.mat files.
  • long_field_names( boolean): False (the default) – A structure’s maximum field name length is 31 characters, which is the maximum length that has been documented. True, a structure’s maximum field name length is 63 characters, which is compatible with MATLAB 7.6+.
  • do_compression(boolean): Matrix compression should be enabled or disabled; the default value is False.
  • oned_as(row, column): Write 1-D NumPy arrays as column vectors if the value is “column.” If “row,” create row vectors from 1-D NumPy arrays.
READ:  Matplotlib plot a line (Detailed Guide)

Let’s take an example by following the below steps:

Import the required libraries or methods using the below python code.

from scipy import io
import numpy as np

Create an array and pass the array to a dictionary to create a dictionary using the below code.

array = [2,3,5,2,7]
array_dict = {"array": array, "label": "example"}
array_dict

Now save the file in Matlab style using the method io.savemat() with file name matlab_array.mat.

io.savemat("matlab_array.mat", array_dict)

From the above code, we have successfully saved the mat file in the current directory of the Jupyter Notebook using the method savemat()

Python Scipy Save And Load Mat File
Python Scipy Save And Load Mat File

To load the saved mat file matlab_array.mat refer to subsection “Python Scipy Load Mat File”.

Read: Python Scipy Stats Kurtosis

Python Scipy Whosmat File

To view variables within a mat file, the method whosmat() of module scipy.io is used.

The syntax is given below.

scipy.io.whosmat(file_name, appendmat=True)

Where parameters are:

file_name(str): The file’s name (without the.mat extension if appendmat==True). open file-like objects may also be passed.
appendmat(boolean): If the ‘.mat extension’ is not already present, add it to the end of the specified filename. True by default.

Let’s take an example by importing the required module using the below python code.

from scipy import io

Now use the method whosmat() to check the variable within the mat file pqfile.mat that we have created in the above subsection “Python Scipy Load Mat File” of this tutorial.

io.whosmat('pqfile.mat')
Python Scipy Whosmat File
Python Scipy Whosmat File

From the output, we can see that the file pqfile.mat contains a variable p of type double.

Also, take a look at some more Python SciPy tutorials.

So, in this tutorial, we have learned about the “Python Scipy Load Mat File” and covered the following topics.

  • Python Scipy Load Mat File
  • Python Scipy Load Mat Struct
  • Python Scipy Load Mat File To Dataframe
  • Python Scipy Load Mat File Hdf5
  • Python Scipy Save And Load Mat File
  • Python Scipy Whosmat File