Python’s SciPy package has a function that saves Python variable into MATLAB’s .mat
file
https://docs.scipy.org/doc/scipy/reference/generated/scipy.io.savemat.html
However, the documentation lacks examples, and I don’t know what is the dictionary of variables it wants as an input.
Say I have a 2D NumPy array A
and a 3D NumPy array B
, how do I save them into a .mat
file called my_arrays.mat
?
Can I save multiple variables in .mat
or do I need a file to each variable?
How to read .mat
files into Python and how do I know to reach variables they have been loaded?
Advertisement
Answer
Examples for saving and loading
JavaScript
x
22
22
1
import scipy.io as sio
2
3
# dummy data
4
A = np.random.randint(0,10,100)
5
B = np.random.randint(0,10,100)
6
7
# collect arrays in dictionary
8
savedict = {
9
'A' : A,
10
'B' : B,
11
}
12
13
# save to disk
14
sio.savemat('my_arrays.mat', savedict)
15
16
#load from disk
17
data = sio.loadmat('my_arrays.mat')
18
19
# alternative way to load from disk:
20
data = {}
21
sio.loadmat('my_arrays.mat', mdict=data)
22