HTML tutorial
CSS3 tutorial
Bootstrap tutorial
JavaScript tutorial
JQuery tutorial
AngularJS tutorial
React tutorial
NodeJS tutorial
PHP tutorial
Python tutorial
Python3 tutorial
Django tutorial
Linux tutorial
Docker tutorial
Ruby tutorial
Java tutorial
C tutorial
C ++ tutorial
Perl tutorial
JSP tutorial
Lua tutorial
Scala tutorial
Go tutorial
ASP.NET tutorial
C # tutorial
We know that NumPy provides us with methods to persist the data in readable formats for Python.But SciPy provides us with interoperability with Matlab as well
We know that NumPy provides us with methods to persist the data in readable formats for Python. But SciPy provides us with interoperability with Matlab as well.
SciPy provides us with the module scipy.io
, which has functions for working with
Matlab arrays.
The savemat()
function allows us to export data in
Matlab format.
The method takes the following parameters:
Export the following array as variable name "vec" to a mat file:
from scipy import io
import numpy as np
arr = np.arange(10)
io.savemat('arr.mat', {"vec": arr})
Note: The example above saves a file name "arr.mat" on your computer.
To open the file, check out the "Import Data from Matlab Format" example below:
The loadmat()
function allows us to import data from a
Matlab file.
The function takes one required parameter:
It will return a structured array whose keys are the variable names, and the corresponding values are the variable values.
Import the array from following mat file.:
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)
{ '__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]]) }
Use the variable name "vec" to display only the array from the matlab data:
...
print(mydata['vec'])
[[0 1 2 3 4 5 6 7 8 9]]
In order to resolve this we can pass an additional argument squeeze_me=True
:
# Import:
mydata = io.loadmat('arr.mat', squeeze_me=True)
print(mydata['vec'])
[0 1 2 3 4 5 6 7 8 9]
Insert the missing method to export data in Matlab format:
from scipy import io import numpy as np arr = np.arange(10) io.('arr.mat', {"vec": arr})