Home > Back-end >  Python: Save Struct in .mat
Python: Save Struct in .mat

Time:04-11

I have Data in Numpy that I want to save in a .mat file. The Data is organized into Packets with 5 Numpy arrays and 1 Scalar Value. How do I save this into a .mat File?

Screenshot from Matlab

I tried using Numpy Records and scipy.io.savemat, and that works for saving Scalar Values into a Matlab Struct, but when I tried to combine differently shaped arrays it raised an Error that the Arrays are mismatched.

mat_data = fromarrays([Data_1,      # Lists containing Numpy Arrays
                       Data_2,
                       Data_3,
                       Data_4,
                       Data_5,
                       Field_1],    # List containing scalars
                      names=['Data_1', 'Data_2', 'Data_3', 'Data_4', 'Data_5', 'Field_1'])

savemat('Filename.mat', {'struct': mat_data})

When I load a .mat file that's structured as I want and save it, it creates a 1xN Cell array with each cell containing one "Row" of the Original Struct, so I wonder if scipy.io even supports this kind of Format.

Example

a = np.zeros(1, 1024)
b = np.random.randint(0, 10)
save_dict = {'Data_1': a, 'Field_1': b}
save_data = [save_dict for _ in range(10)]

# This should create a 1x10 Struct with 2 Fields
savemat('Test.mat', {'struct': save_data)

The Data in save_data is the structurally the same as what I get when I load a correctly structured .mat file but when I load the Test.mat File in Matlab it's represented as a 1x10 Cell Array

CodePudding user response:

Making a structured array from an array and integer takes some care (fromarrays is best for like sized arrays):

In [31]: arr = np.array([(a,b)], 'O,i')
In [32]: arr
Out[32]: 
array([(array([[0., 0., 0., ..., 0., 0., 0.]]), 0)],
      dtype=[('f0', 'O'), ('f1', '<i4')])
In [33]: io.savemat('test.mat', {'data':arr})
In [34]: io.loadmat('test.mat')
Out[34]: 
{'__header__': b'MATLAB 5.0 MAT-file Platform: posix, Created on: Sun Apr 10 08:57:53 2022',
 '__version__': '1.0',
 '__globals__': [],
 'data': array([[(array([[0., 0., 0., ..., 0., 0., 0.]]), array([[0]], dtype=int32))]],
       dtype=[('f0', 'O'), ('f1', 'O')])}

In Octave

>> load test.mat
>> size(data.f0)
ans =

      1   1024

>> size(data.f1)
ans =

   1   1

Earlier I explored saving complex struct in

Convert multiple Python dictionaries to MATLAB structure array with scipy.io savemat

CodePudding user response:

Using the Package Mat4Py it worked!

  • Related