4

I have a .mat file that contains two DateTime arrays in string format. The arrays are like:

A = ["15-Nov-2014 22:42:16",
         "16-Dec-2014 04:14:07",
         "20-Jan-2015 17:05:32"]

I saved the two String arrays in a .mat file. I tried to load them in Python with this command:

import hdf5storage
Input = hdf5storage.loadmat('Input.mat')

or this command:

import scipy
Input = scipy.io.loadmat('Input.mat')

Both lead to reading a dictionary in Python which is expected but I cannot see the name of the two arrays as the dictionary keys.

Any ideas?

3
  • 1
    Apparently there is no documented solution for reading MATLAB strings from HDF5 storage (MATLAB strings are objects, with undocumented internal storage format). I recommend you converting the strings to character arrays. Commented Jan 8, 2020 at 0:02
  • @Rotem It worked! In MATLAB, I converted the strings to chars, then save under a .mat file then loaded in Python with scipy.io.loadmat. Thank you so much for your answer! Please write this hint as an answer so that I can accept and rate it. Commented Jan 8, 2020 at 4:12
  • I posted am answer. Please note that mat file is not in HDF5 format, and the strings in Python are read in utf-16 format (numpy array of type '<U20'). Commented Jan 8, 2020 at 7:06

1 Answer 1

6

I recommend you converting the strings to character arrays.

Apparently there is no documented solution for reading MATLAB strings from HDF5 storage (MATLAB strings are objects, with undocumented internal storage format).

Saving character array to Input.mat in MATLAB (not in HDF5 format):

A = ["15-Nov-2014 22:42:16"; "16-Dec-2014 04:14:07"; "20-Jan-2015 17:05:32"];

% Convert A from array of strings to 2D character array.
% Remark: all strings must be the same length
A = char(A); % 3*20 char array

% Save A to mat file (format is not HDF5).
save('Input.mat', 'A');

Reading A in Python using scipy.io.loadmat:

from scipy import io

# Read mat file
Input = io.loadmat('Input.mat')  # Input is a dictioanry {'A': array(['15-Nov-2014 ...pe='<U20'), ...}

# Get A from Input (A stored in MATLAB - character arrays in MATLAB are in type utf-16)
A = Input['A'];  # A is 2D numpy array of type '<U20' array(['15-Nov-2014 22:42:16', '16-Dec-2014 04:14:07', ...], dtype='<U20')
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.