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** ** in a module

`loadmat()`

*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

returns *loadmat()*

which is the dictionary containing loaded matrices as values and variable names as keys.*m_dict*

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

Go to website

and write the below code to save a variable *https://matlab.mathworks.com/*`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

that contains a variables *pqfile.mat*`p`

. Then click on Download the button to download the file on your computer.

Now, we are going to load the file using the method `loadmat()`

using the below code.

```
from scipy.io import loadmat
loadmat('pqfile.mat')
```

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

of Python Scipy.*loadmat()*

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

that is accepted by the method *struct_as_record*

.*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

of Pandas. For instance, we will use the same mat file *Dataframe()*`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

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

To access the values of variables in the dictionary. Here we will use the method

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.*get()*

And pass the returned value to the method

of Pandas to convert the values to dataframe as shown below.*Dataframe()*

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

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

`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

can not load the *loadmat()*

of *HDF5*

type of file. The HDF5 binary data format has a Pythonic interface called the h5py package.*h5*

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.

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

using the below python code.*h5py*

`pip install h5py`

Import the module `h5py`

using the below code.

`import h5py`

Read the file

that is created by Matlab using the method *myrndarray.h5*

of module *File()*`h5py`

.

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

Now use the method

of the dictionary to know about the file info using the below code.*get()*

`f_data.get('DS1')`

The output shows the file format HDF5 with a key equal to DS1 and shapes equally to

. This is how to read the file with the format *(10,5)*

or *hdf5*

.*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

extension, we will use the method *.mat*

of module *savemat()*

.*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.

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()*

To load the saved mat file

refer to subsection “Python Scipy Load Mat File”.*matlab_array.mat*

Read: Python Scipy Stats Kurtosis

## Python Scipy Whosmat File

To view variables within a mat file, the method

of module *whosmat()*

is used.*scipy.io*

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

to check the variable within the mat file *whosmat()*

that we have created in the above subsection *pqfile.mat***“Python Scipy Load Mat File”** of this tutorial.

`io.whosmat('pqfile.mat')`

From the output, we can see that the file

contains a variable *pqfile.mat*

of type *p*

.*double*

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

- Python Scipy Stats Mode
- Scipy Butterworth Filter
- Python Scipy Stats Fit
- Python Scipy Minimize
- Python Scipy Exponential
- Scipy Normal Distribution
- Python Scipy Curve Fit

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

Python is one of the most popular languages in the United States of America. I have been working with Python for a long time and I have expertise in working with various libraries on Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… I have experience in working with various clients in countries like United States, Canada, United Kingdom, Australia, New Zealand, etc. Check out my profile.