I have a .npz file that I would like to save as a .mat file.
The file A.npz contains A['arr_0', 'arr_1', 'arr_2']
Currently, I am saving each one individually using the following:
import scipy.io as sio
a1 = A['arr_0']
sio.savemat('a1.mat', mdict={'a1': a1}
for each arr_i within A.npz.
Is there a simple way to save all the contents into a .mat (i.e. via cell format)? Or should I just create a script to simply save them all in a loop like fashion?
Create a npz:
In [147]: np.savez('test.npz',x=np.arange(3),y=np.ones((3,3)),z=np.array(3))
load; data is the dictionary of files/variables; load by indexing:
In [148]: data = np.load('test.npz')
In [149]: list(data.keys())
Out[149]: ['z', 'y', 'x']
In [150]: data['x']
Out[150]: array([0, 1, 2])
Save a similar dictionary to the .mat:
In [151]: io.savemat('a1.mat', mdict={'x':data['x'],'y':data['y'],'z':data['z']})
In [152]: io.loadmat('a1.mat')
Out[152]:
{'__globals__': [],
'__header__': b'MATLAB 5.0 MAT-file Platform: posix, Created on: Thu Feb 15 09:52:42 2018',
'__version__': '1.0',
'x': array([[0, 1, 2]]),
'y': array([[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.]]),
'z': array([[3]])}
alternative constructs:
io.savemat('a1.mat', mdict={key:data[key] for key in data.keys()})
or even:
io.savemat('a1.mat', mdict=data)
since data is a dictionary.
One-liner for shell scripts, etc.:
python -c "import pylab, scipy.io; scipy.io.savemat('tmp.mat', pylab.np.load('tmp.npz'))"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With