Skip to content
Advertisement

Loading Matlab files into Python

I am attempting to understand the difference between loading a data file into Python and into Matlab in order to translate some code. I have a line of code that goes:

load('USGS_1995_Library')

When I run the code in Matlab I know that the data is in workspace. There is a 224×501 double called datalib and a 501×29 double called names. The very next line of code is:

wavlen=datalib(:,1);    # Wavelengths in microns

Thus I know that Matlab keeps the already established variables in the code without me needing to go back and parse through the data to define it.

Is there anything in Python that can emulate that same functionality? I did some research and found that I can use scipy.io to load a Matlab file (the file is a Matlab file). I know this will enable me to open the Matlab file using Python but does anybody have any experience and know if it will also load the variables and their definitions/values so that it can be used in the rest of the code?

Advertisement

Answer

When loading a .mat file into python using scipy.io.loadmat, you’ll end up with a dictionary of the variables contained in the file (plus some metadata). So you can access the variables as you would any other dictionary in python. For example:

import scipy.io as sio

mat_file = sio.loadmat('USGS_1995_Library.mat')

datalib = mat_file['datalib']
names = mat_file['names']

However, I don’t think that there is any way to automatically turn the objects into variables in the same way that you would be loading them into MATLAB, short of using the risky methods outlined in this answer

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement