Load pickle files in Matlab

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

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

Thanks to Tim R for this second method.

2 responses to “Load pickle files in Matlab”

  1. 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 ?

Leave a comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s