9ab15326d5
Signed-off-by: David Rotermund <54365609+davrot@users.noreply.github.com>
2.4 KiB
2.4 KiB
Numpy: Dealing with Matlab files
{:.no_toc}
* TOC {:toc}The goal
We want to read and write Matlab files under Python.
Questions to David Rotermund
Reminder: Learning Python as Matlab user Please read NumPy for MATLAB users
Mat files under Python
MATLAB < 7.3 format mat files
This is a job for scipy.io
loadmat(file_name[, mdict, appendmat]) | Load MATLAB file. |
savemat(file_name, mdict[, appendmat, …]) | Save a dictionary of names and arrays into a MATLAB-style .mat file. |
whosmat(file_name[, appendmat]) | List variables inside a MATLAB file. |
Read
Under Matlab we create a test file
>> A = rand(10,100);
>> save -v7 Test_1.mat A
Under Python we look into the file for information:
import scipy.io as sio
Info = sio.whosmat("Test_1.mat")
print(Info) # --> [('A', (10, 100), 'double')]
And we can read the data:
import numpy as np
import scipy.io as sio
mat_data = sio.loadmat("Test_1.mat")
print(
mat_data.keys()
) # -> dict_keys(['__header__', '__version__', '__globals__', 'A'])
a = mat_data["A"]
print(type(a)) # --> <class 'numpy.ndarray'>
print(a.dtype) # --> float64
print(a.shape) # --> (10, 100)
Write
Under Python we generate a .mat file:
import numpy as np
import scipy.io as sio
myrng = np.random.default_rng()
A: np.ndarray = myrng.random((10, 100), dtype=np.float64)
B: str = "Hellp world!"
mdic = {"A": A, "ImportantMessage": B}
sio.savemat("Test_2.mat", mdic)
And read it in under Matlab:
>> load Test_2.mat
>> whos
Name Size Bytes Class Attributes
A 10x100 8000 double
ImportantMessage 1x12 24 char
>> ImportantMessage
ImportantMessage =
'Hellp world!'