【问题标题】:Load a .mat file including string array to Python 3.6将包含字符串数组的 .mat 文件加载到 Python 3.6
【发布时间】:2020-01-07 20:01:48
【问题描述】:

我有一个 .mat 文件,其中包含两个字符串格式的 DateTime 数组。数组如下:

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

我将两个字符串数组保存在一个 .mat 文件中。我尝试使用以下命令在 Python 中加载它们:

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

或者这个命令:

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

两者都会导致在 Python 中读取字典,这是预期的,但我看不到两个数组的名称作为字典键。

有什么想法吗?

【问题讨论】:

  • 显然没有记录从 HDF5 存储读取 MATLAB 字符串的解决方案(MATLAB 字符串是对象,具有未记录的内部存储格式)。我建议您将字符串转换为字符数组。
  • @Rotem 成功了!在 MATLAB 中,我将字符串转换为字符,然后保存在 .mat 文件下,然后使用 scipy.io.loadmat 在 Python 中加载。非常感谢您的回答!请将此提示写为答案,以便我接受并评分。
  • 我发布了答案。请注意mat文件不是HDF5格式,Python中的字符串是以utf-16格式读取的('<U20'类型的numpy数组)。

标签: python string matlab


【解决方案1】:

我建议您将字符串转换为字符数组。

显然,对于从 HDF5 存储读取 MATLAB 字符串没有文档化的解决方案(MATLAB 字符串是对象,具有未记录的内部存储格式)。

在MATLAB中将字符数组保存到Input.mat(不是HDF5格式):

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');

使用 scipy.io.loadmat 在 Python 中读取A

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')

【讨论】:

    猜你喜欢
    • 2017-12-27
    • 1970-01-01
    • 1970-01-01
    • 2011-06-16
    • 1970-01-01
    • 2016-07-17
    • 1970-01-01
    • 1970-01-01
    • 2019-01-12
    相关资源
    最近更新 更多