2

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 224x501 double called datalib and a 501x29 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?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
A.Torres
  • 413
  • 1
  • 6
  • 16
  • 1
    There are a number of SO questions about using `loadmat`, which should be easy to find. Getting variables from the loaded dictionary is easy. But if the MATLAB variables are anything but matrices, the resulting `numpy` array can be hard to understand, since `loadmat` is trying to recreate a foreign structure as best it can. – hpaulj Jul 27 '18 at 19:13
  • 2
    I strongly advise you not to do this in even in MATLAB. It may seem convenient at first, but it tends to make things harder down the road as your code grows. Code that uses a variable can end up hundreds of lines away from where it was loaded, making it hard to track down where the variable came from. If you end up loading a second file it can be hard to remember what variable came from where. It confuses the build-in code checkers for MATLAB. Overall I strongly advise you to use he `data = load('fname')` structure from the get-go, I suspect your future self will thank you. – TheBlackCat Jul 27 '18 at 19:53

1 Answers1

3

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

sacuL
  • 49,704
  • 8
  • 81
  • 106