【问题标题】:Adding a new variable to a .mat file using the Python package hdf5storage使用 Python 包 hdf5storage 将新变量添加到 .mat 文件
【发布时间】:2015-03-31 16:13:52
【问题描述】:

是否可以使用 Python 包 hdf5storage 向 .mat 文件 (v7.3) 添加新变量?


例子:

我用 Matlab 写的:

test = {'Hello', 'world!'; 'Good', 'morning'; 'See', 'you!'};
save('data.mat', 'test', '-v7.3') % v7.3 so that it is readable by h5py

在 Python 中,我想向data.mat 添加一个新变量。我该怎么做才能达到以下目的:

我试过了:

import hdf5storage # get code on https://pypi.python.org/pypi/hdf5storage/0.1.3
import numpy as np

matcontent = {}
matcontent[u'some_numbers'] = np.array([10, 50, 20]) # each key must be a unicode string
hdf5storage.write(matcontent, '.', 'data.mat', matlab_compatible=True)

但它会覆盖 data.mat 而不是添加新变量。

【问题讨论】:

  • 一定要用hdf5storage吗? Scipy 也提供此功能。
  • scipy 仅支持版本 5 格式。

标签: python matlab hdf5 hdf5storage


【解决方案1】:

到目前为止,我知道这是不可能的。 TheBlackCat 提供的答案在您重写文件时并不真正适用。我倾向于拥有非常大的 matlab 文件,我通常不想完全阅读这些文件,而是有选择地读取或写入。这是 .mat 文件中使用的底层 HDF5 格式的一大优势(连同引用)。 python 包 hdf5storage 仍然是 0.xx 版本,所以我想这将在未来的版本中出现。

【讨论】:

    【解决方案2】:

    您正在创建新数据,然后将新数据写入文件。这会覆盖文件。您需要加载原始的.mat 文件,附加到它,然后再次保存。

    import hdf5storage
    import numpy as np
    
    matcontent = hdf5storage.loadmat('data.mat')
    matcontent[u'some_numbers'] = np.array([10, 50, 20])
    hdf5storage.savemat('data.mat', matcontent)
    

    然后在 Matlab 中

    >> whos -file data.mat
          Name              Size            Bytes  Class    Attributes
    
          some_numbers      1x3                24  int64              
          test              3x2               730  cell   
    

    【讨论】:

      猜你喜欢
      • 2018-08-08
      • 2011-01-09
      • 1970-01-01
      • 1970-01-01
      • 2012-01-20
      • 2017-08-27
      • 2012-05-28
      • 2012-05-17
      • 1970-01-01
      相关资源
      最近更新 更多