0

Is it possible to add a new variable to a .mat file (v7.3) using the Python package hdf5storage?


Example:

I wrote in Matlab:

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

enter image description here

In Python I would like to add a new variable to data.mat. How can I do so, to achieve something like:

enter image description here

I tried:

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)

but it overwrites data.mat instead of adding a new variable.

Franck Dernoncourt
  • 62,576
  • 61
  • 286
  • 446

2 Answers2

1

You are creating new data, then writing that new data to a file. That overwrites the file. You need to load the original .mat file, append to it, then save again.

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)

Then in Matlab

>> whos -file data.mat
      Name              Size            Bytes  Class    Attributes

      some_numbers      1x3                24  int64              
      test              3x2               730  cell   
TheBlackCat
  • 8,073
  • 3
  • 20
  • 29
1

So far I know this is not possible. The answer provided by TheBlackCat is not really applicable as you are rewriting you file. I tend to have really big matlab files which I won't normally want to read completely and instead read or write selectively. That's the big advantage (together with referencing) of the underlying HDF5 format used in the .mat files. The python package hdf5storage is still in 0.xx version so I suppose this will come in future versions.