MATLAB: Do I receive the error “TypeError: unsupported data type returned from MATLAB” when attempting to load a .mat file in Python

.mat fileengineMATLABpythontypeerror

I am attempting to load a .mat file with the MATLAB API for Python, as shown:
 
import matlab.engine
eng = matlab.engine.start_matlab()
eng.load('my_file.mat')
eng.quit()
But I receive an error on the line calling the "load" function, stating: ERROR: TypeError: unsupported data type returned from MATLAB

Best Answer

This error message occurs when your .mat file contains variables with types unsupported by the MATLAB API for Python.
When a MATLAB function, called via the MATLAB Engine API for Python, returns output arguments, the API converts the data into equivalent Python data types. However, not all MATLAB data types can be converted. The following MATLAB data types cannot be converted, and thus cause an unsupported type or value error when they are returned:
- Categorical array
- char array (M-by-N)
- Cell array (M-by-N)
- Function handle
- Sparse array
- Structure array
- Table
- MATLAB value objects
- Non-MATLAB objects
One workaround involves using the "evalc" function, via MATLAB Engine, to call the "load" function (instead of calling the "load" function directly). What this allows you to do is keep the loaded variables in the MATLAB Engine workspace so that the API does not attempt to convert them to Python data types. Then you can pull the variables from the MATLAB Engine workspace into the Python environment, as needed, after doing any necessary conversion.
For example:
 
import matlab.engine
eng = matlab.engine.start_matlab()
# Use evalc to load the .mat file so that it is kept in the MATLAB Engine workspace.
# This stops the API from attempting to convert the variables Python types on load.
eng.evalc("s = load('my_file.mat');")
# Now we can grab the data, as needed, from the MATLAB Engine workspace and pull it into Python.
# At this point the API will need to convert the data to Python types.
myVar1 = eng.eval("s.myVar1");
print (myVar1)
# With unsupported types, we can convert the variables to supported types while they are in
# the MATLAB Engine workspace, and then pull the supported representation into Python.
eng.evalc("dt = num2cell(s.myDatetimes)")
myDateStrings = eng.eval("cellfun(@datestr, dt, 'UniformOutput', false)")
print (myDateStrings)
eng.quit()