Updated March 2020
It’s easy enough to load .mat
files in Python via the scipy.io.loadmat function. But what about loading .pickle files into Matlab? You need to do a little more work! It’s a bit roundabout, but if python is installed and on your path, you can call it from Matlab to save the data in the .mat format which Matlab can load, like so:
function [a] = loadpickle(filename)
if ~exist(filename,'file')
error('%s is not a file',filename);
end
outname = [tempname() '.mat'];
pyscript = ['import pickle;import sys;import scipy.io;file=open("' filename '", "rb");dat=pickle.load(file);file.close();scipy.io.savemat("' outname '.dat")'];
system(['python -c "' pyscript '"']);
a = load(outname);
end
In newer versions of Matlab, there’s an even simpler method thanks to the direct Python support in Matlab. Assuming you’ve set up Matlab to use the right Python version, you can simply use:
% Filename is the name of the file.
fid = py.open(filename,'rb');
data = py.pickle.load(fid);
2 responses to “Load pickle files in Matlab”
[…] And that’s pretty much all there is to it. You can use a similar process to call Python from Matlab. See also this post about reading pickle files in Matlab. […]
When I try this I seem to be getting this error – File “/path-to-python-packages/scipy/io/matlab/mio5.py”, line 857, in put_variables
for name, var in mdict.items():
AttributeError: ‘list’ object has no attribute ‘items’
I am using scipy 0.13 – Any Idea what could be going wrong here ?