SciPy Matlab Arrays
NumPy provides a way to save data in a Python-readable format.
SciPy provides methods for interacting with Matlab.
SciPy's scipy.io module provides many functions to handle Matlab arrays.
Exporting Data in Matlab Format
savemat()The method can export data in Matlab format.
The method parameters are:- filename- The file name to save the data.
- mdict- A dictionary containing the data.
- do_compression- A boolean value specifying whether the resulting data is compressed. Defaults to False.
Export the array to a mat file as variable "vec":
Example
import numpy as np
arr = np.arange(10)
io.savemat('arr.mat', {"vec": arr})
Note:The code above saves 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:
- filename- The file name of the saved data.
It returns a structured array whose keys are variable names and whose corresponding values are the variable values.
The following example imports an array from a mat file:
Example
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 returned 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]])
}Using the variable name "vec" to display only the array of matlab data:Example
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 returned result is as follows:
[[0 1 2 3 4 5 6 7 8 9]]
From the result, you can see that the array was originally one-dimensional, but when extracted, it gains an extra dimension and becomes a two-dimensional array.
To solve this problem, you can pass an additional parameter.squeeze_me=True:
Example
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 returned result is as follows:
[0 1 2 3 4 5 6 7 8 9]Other Extensions