Easy Tutorial
❮ Scipy Module Scipy Graph ❯

SciPy Matlab Arrays

NumPy provides a method to save data in a Python-readable format.

SciPy offers methods for interacting with Matlab.

The scipy.io module in SciPy provides many functions to handle Matlab arrays.

Exporting Data in Matlab Format

The savemat() method can export data in Matlab format.

Exporting an array as the variable "vec" to a mat file:

Example

from scipy import io
import numpy as np

arr = np.arange(10)

io.savemat('arr.mat', {"vec": arr})

Note: The above code will save a file named "arr.mat" on your computer.

Importing Data in Matlab Format

The loadmat() method can import data in Matlab format.

The method parameters:

Returns a structured array where the keys are the variable names and the corresponding values are the variable values.

The following example imports an array from a mat file:

Example

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)

The return result is as follows:

{
   '__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]])
}

Example

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['vec'])

The return result is as follows:

[[0 1 2 3 4 5 6 7 8 9]]

From the result, it can be seen that the array was originally one-dimensional, but it has gained an extra dimension and become two-dimensional when extracted.

To solve this issue, an additional parameter squeeze_me=True can be passed:

Example

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', squeeze_me=True)

print(mydata['vec'])

The return result is as follows:

[0 1 2 3 4 5 6 7 8 9]
❮ Scipy Module Scipy Graph ❯